一、摘要

  1、所需软件列表:

    1) tomcat : apache-tomcat-7.0.54  服务端容器

    2) Intellij: Intellij IDEA 2016.3.1 开发工具  

    3) Syslog: SQLyog Community   数据库工具

  2. 步骤简述:

   1) 新建一个 Java 项目, 依次选择Spring--->Spring MVC--->Finish;

   2) web目录下新建前台页面相关目录(css/js/page等);

     3) WEB-INF文件夹下新建如下两个文件夹:
    lib: 用于存放项目相关jar包,项目如已导入maven可无视该步骤;
    resources: 用于存放Spring,Mybatis等相关配置文件。
    4)src目录下用于存放服务端相关代码

  完成后的工程目录如下:

  

二、Spring配置:

1、需要导入的包如下:

  

2、 相关配置文件

  1)web.xml配置(用于配置Spring 相关配置项:上下文、日志、字符集、监听器等)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"> <!-- 告知javaEE容器,哪些内容需要添加到上下文中去 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param> <!-- 加载LOG4J -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.xml</param-value>
</context-param> <context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param> <!-- 动态设置项目的运行路径 -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>mvc.root</param-value>
</context-param> <!-- 配置静态资源 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/static/*</url-pattern>
</servlet-mapping> <!-- 配置springmvc的前端控制器 -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 默认情况下:DispatcherServlet会寻找WEB-INF下,命名规范为[servlet-name]-servlet.xml文件。
如:在上例中,它就会找/WEB-INF/mvc-servlet.xml
如果需要修改,需要在web.xml中的<servlet>标记中增加 <init-param>。。。</init-param>:-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- spring框架提供的字符集过滤器 -->
<!-- spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用于解决POST方式造成的中文乱码问题 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener> <welcome-file-list>
<welcome-file>/page/index.html</welcome-file>
</welcome-file-list>
</web-app>

  2)spring-servlet.xml配置(用于配置SpringMVC相关: 注解、视图解析器、自动扫描等)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <bean id="fastJsonHttpMessageConverter"
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>application/json</value>
</list>
</property>
<property name="features">
<list>
<!-- 输出key时是否使用双引号 -->
<value>QuoteFieldNames</value>
<!-- 是否输出值为null的字段 -->
<value>WriteMapNullValue</value>
<!-- 数值字段如果为null,输出为0,而非null -->
<value>WriteNullNumberAsZero</value>
<!-- List字段如果为null,输出为[],而非null -->
<value>WriteNullListAsEmpty</value>
<!-- 字符类型字段如果为null,输出为"",而非null -->
<value>WriteNullStringAsEmpty</value>
<!-- Boolean字段如果为null,输出为false,而非null -->
<value>WriteNullBooleanAsFalse</value>
<!-- null String不输出 -->
<value>WriteNullStringAsEmpty</value>
<!-- Date的日期转换器 -->
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
<!-- 启动注解,注册服务,如验证框架、全局类型转换器-->
<mvc:annotation-driven>
<mvc:message-converters>
<ref bean="fastJsonHttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven> <!-- 静态资源默认servlet配置
(1)加入对静态资源的处理:js,gif,png
(2)允许使用"/"做整体映射
会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,
是spring MVC为@Controllers分发请求所必须的。
并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,
读写XML的支持(JAXB,读写JSON的支持(Jackson
-->
<mvc:default-servlet-handler/> <!-- 启动自动扫描 -->
<context:component-scan base-package="com.test">
<!-- 制定扫包规则 ,只扫描使用@Controller注解的JAVA类 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan> <!-- 配置视图解析器 -->
<!--prefix和suffix:查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀),
比如传进来的逻辑视图名为WEB-INF/page/hello,则该该jsp视图页面应该存放在“WEB-INF/page/hello.html”; -->
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/page"></property>
<property name="suffix" value=".html"></property>
</bean>
</beans>

  3) datasource.properties(用于配置数据库文件)

jdbc.driver= com.mysql.jdbc.Driver
jdbc.url= jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
jdbc.username= root
jdbc.password= root

  4)  log4j.xml(用于配置记录日志文件)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "F:\SpringMybatis测试\SpringMVC_Mybatis\src\webapp\WEB-INF\conf\log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jakarta.apache.org/log4j/ "> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n"/>
</layout>
</appender> <appender name="DEBUG" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="${ssm.root}/ssm-debug.log"/>
<param name="Append" value="true"/>
<param name="MaxFileSize" value="10240KB"/>
<param name="MaxBackupIndex" value="1000"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="DEBUG"/>
<param name="LevelMax" value="DEBUG"/>
</filter>
</appender> <appender name="INFO" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="${ssm.root}/ssm-info.log"/>
<param name="Append" value="true"/>
<param name="MaxFileSize" value="10240KB"/>
<param name="MaxBackupIndex" value="1000"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="INFO"/>
<param name="LevelMax" value="INFO"/>
</filter>
</appender> <appender name="WARN" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="${ssm.root}/ssm-warn.log"/>
<param name="Append" value="true"/>
<param name="MaxFileSize" value="10240KB"/>
<param name="MaxBackupIndex" value="1000"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="WARN"/>
<param name="LevelMax" value="WARN"/>
</filter>
</appender> <appender name="ERROR" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="${ssm.root}/ssm-error.log"/>
<param name="Append" value="true"/>
<param name="MaxFileSize" value="10240KB"/>
<param name="MaxBackupIndex" value="1000"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%c %d{yyyy-MM-dd HH:mm:ss} -- %p -- %m%n"/>
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="ERROR"/>
<param name="LevelMax" value="ERROR"/>
</filter>
</appender> <root>
<priority value="INFO"/>
<appender-ref ref="STDOUT"/>
<appender-ref ref="DEBUG"/>
<appender-ref ref="INFO"/>
<appender-ref ref="WARN"/>
<appender-ref ref="ERROR"/>
</root> </log4j:configuration>

  5) log4j,dtd(主要是对相应.xml进行约束验证用的)

<?xml version="1.0" encoding="UTF-8" ?>

<!ELEMENT log4j:configuration (renderer*, throwableRenderer?,
appender*,plugin*, (category|logger)*,root?,
(categoryFactory|loggerFactory)?)> <!ATTLIST log4j:configuration
xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/"
threshold (all|trace|debug|info|warn|error|fatal|off|null) "null"
debug (true|false|null) "null"
reset (true|false) "false"
> <!ELEMENT renderer EMPTY>
<!ATTLIST renderer
renderedClass CDATA #REQUIRED
renderingClass CDATA #REQUIRED
> <!ELEMENT throwableRenderer (param*)>
<!ATTLIST throwableRenderer
class CDATA #REQUIRED
> <!ELEMENT appender (errorHandler?, param*,
rollingPolicy?, triggeringPolicy?, connectionSource?,
layout?, filter*, appender-ref*)>
<!ATTLIST appender
name CDATA #REQUIRED
class CDATA #REQUIRED
> <!ELEMENT layout (param*)>
<!ATTLIST layout
class CDATA #REQUIRED
> <!ELEMENT filter (param*)>
<!ATTLIST filter
class CDATA #REQUIRED
> <!ELEMENT errorHandler (param*, root-ref?, logger-ref*, appender-ref?)>
<!ATTLIST errorHandler
class CDATA #REQUIRED
> <!ELEMENT root-ref EMPTY> <!ELEMENT logger-ref EMPTY>
<!ATTLIST logger-ref
ref CDATA #REQUIRED
> <!ELEMENT param EMPTY>
<!ATTLIST param
name CDATA #REQUIRED
value CDATA #REQUIRED
> <!ELEMENT priority (param*)>
<!ATTLIST priority
class CDATA #IMPLIED
value CDATA #REQUIRED
>
<!ELEMENT level (param*)>
<!ATTLIST level
class CDATA #IMPLIED
value CDATA #REQUIRED
> <!ELEMENT category (param*,(priority|level)?,appender-ref*)>
<!ATTLIST category
class CDATA #IMPLIED
name CDATA #REQUIRED
additivity (true|false) "true"
> <!ELEMENT logger (param*,level?,appender-ref*)>
<!ATTLIST logger
class CDATA #IMPLIED
name CDATA #REQUIRED
additivity (true|false) "true"
> <!ELEMENT categoryFactory (param*)>
<!ATTLIST categoryFactory
class CDATA #REQUIRED> <!ELEMENT loggerFactory (param*)>
<!ATTLIST loggerFactory
class CDATA #REQUIRED> <!ELEMENT appender-ref EMPTY>
<!ATTLIST appender-ref
ref CDATA #REQUIRED
> <!-- plugins must have a name and class and can have optional parameters -->
<!ELEMENT plugin (param*, connectionSource?)>
<!ATTLIST plugin
name CDATA #REQUIRED
class CDATA #REQUIRED
> <!ELEMENT connectionSource (dataSource?, param*)>
<!ATTLIST connectionSource
class CDATA #REQUIRED
> <!ELEMENT dataSource (param*)>
<!ATTLIST dataSource
class CDATA #REQUIRED
> <!ELEMENT triggeringPolicy ((param|filter)*)>
<!ATTLIST triggeringPolicy
name CDATA #IMPLIED
class CDATA #REQUIRED
> <!ELEMENT rollingPolicy (param*)>
<!ATTLIST rollingPolicy
name CDATA #IMPLIED
class CDATA #REQUIRED
> <!ELEMENT root (param*, (priority|level)?, appender-ref*)> <!ELEMENT log4j:eventSet (log4j:event*)>
<!ATTLIST log4j:eventSet
xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/"
version (1.1|1.2) "1.2"
includesLocationInfo (true|false) "true"
> <!ELEMENT log4j:event (log4j:message, log4j:NDC?, log4j:throwable?,
log4j:locationInfo?, log4j:properties?) > <!ATTLIST log4j:event
logger CDATA #REQUIRED
level CDATA #REQUIRED
thread CDATA #REQUIRED
Date CDATA #REQUIRED
time CDATA #IMPLIED
> <!ELEMENT log4j:message (#PCDATA)>
<!ELEMENT log4j:NDC (#PCDATA)> <!ELEMENT log4j:throwable (#PCDATA)> <!ELEMENT log4j:locationInfo EMPTY>
<!ATTLIST log4j:locationInfo
class CDATA #REQUIRED
method CDATA #REQUIRED
file CDATA #REQUIRED
line CDATA #REQUIRED
> <!ELEMENT log4j:properties (log4j:data*)> <!ELEMENT log4j:data EMPTY>
<!ATTLIST log4j:data
name CDATA #REQUIRED
value CDATA #REQUIRED
>

 6)applicationContext.xml(Mybatis sqlSessionFactoryBuilder相关配置及Spring AOP等)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <!-- 开启自动扫包 -->
<context:component-scan base-package="com.test">
<!--制定扫包规则,不扫描@Controller注解的JAVA类,其他的还是要扫描 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan> <!-- 启动AOP支持 -->
<aop:aspectj-autoproxy/> <!-- 引入外部数据源配置信息 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:datasource.properties</value>
</property>
</bean> <!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean> <!-- 配置Session工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 加载mybatis.mapper.xml文件 -->
<property name="mapperLocations" value="classpath*:UserMapper.xml"></property>
<!-- 自动扫描需要定义类别名的包,将包内的JAVA类的类名作为类别名 -->
<property name="typeAliasesPackage" value="com.test.pojo"></property>
</bean> <!-- 自动扫描所的Mapper接口与文件 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.test.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean> <!-- 配置事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- 定义操作通知,指定事务管理器 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="save*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="insert*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="update*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="load*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="search*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice> <aop:config>
<!-- 配置一个切入点 -->
<aop:pointcut id="serviceMethods" expression="execution(* com.test.service.impl.*ServiceImpl.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods" />
</aop:config> </beans>

  7) UserMapper.xml(Mybatis 配置文件,用于生成所需的SQL)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.dao.UserDAO">
<!-- 自定义返回结果集 -->
<resultMap id="userMap" type="com.test.pojo.UserBean" >
<id property="id" column="id" javaType="java.lang.Integer"></id>
<result property="name" column="name" javaType="java.lang.String"></result>
<result property="age" column="age" javaType="java.lang.Integer"></result>
</resultMap> <!--查-->
<select id="selectAllUser" resultMap="userMap">
select * from user
</select> <!--#{}:占位符,可用于替换动态内容,防止SQL注入
%{}:拼接sql串,可用于替换静态内容,如表名,数据库连接方式等,不能防止sql注入-->
<!--根据id查询单个用户-->
<select id="selectSingleUser" parameterType="java.lang.Integer" resultMap="userMap">
select * from user
<if test=" id != null">
where id=#{id,jdbcType=INTEGER}
</if>
</select> <select id="countUsers" resultType="int">
select count(*) from user where 1=1
</select> <!--choose, when, otherwise: 等价于swicth case条件执行查询语句
bind: 用于执行左右模糊匹配字段的查询-->
<select id="selectOneUserInfo" resultMap="userMap">
select * from user
<!--<choose>-->
<!--<when test="id != null">-->
<!--where id=#{id,jdbcType=INTEGER}-->
<!--</when>-->
<!--<when test="name != null">-->
<!--where name like #{name}-->
<!--</when>-->
<!--<otherwise>-->
<!--where 1=1-->
<!--</otherwise>-->
<!--</choose>-->
<where>
<if test="id != null">
id=#{id,jdbcType=INTEGER}
</if>
<if test="name != null">
<bind name="username" value="'%' + name + '%'" />
and name like #{username}
</if>
</where>
</select> <!--增-->
<!--如果数据库支持自动生成主键的字段,可以使用useGeneratedKys+keyProperty字段来制定主键-->
<insert id="insertUser" parameterType="java.util.List" useGeneratedKeys="true"
keyProperty="id">
insert into user (id, name, age) values
<foreach collection="list" item="user" separator=",">
(#{user.id},#{user.name},#{user.age})
</foreach>
</insert> <!--改-->
<update id="updateUserInfo">
update user
<set>
<if test="user.id != null">id=#{user.id},</if>
<if test="user.name != null">name=#{user.name},</if>
<if test="user.age != null">age=#{user.age}</if>
</set>
where id=#{id}
</update> <!--删-->
<delete id="deleteUser">
delete from user
<trim prefix="WHERE" prefixOverrides="AND | OR">
<if test="id != null">
WHERE id = #{id,jdbcType=INTEGER}
</if>
<!--<if test="name != null and name.length()>0">-->
<!--AND WHERE name = #{name}-->
<!--</if>-->
</trim>
</delete>
</mapper>

 三、 服务端代码

  服务端代码使用MVC模式,使得视图(界面显示)、模型(数据)及控制器(业务逻辑)三者分离的方式组织代码,将业务逻辑聚集到一个部件里,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。
具体的编码实现如下:

1)User实体类:

package com.test.pojo;

public class UserBean{
private int id;
private String name;
private int age; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "UserBean{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}

 2) 控制器类:

package com.test.controller;

import com.test.pojo.UserBean;
import com.test.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*; import javax.jws.WebMethod;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; @RestController()
public class UserController {
@Autowired
private UserService userService; @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
public List getUserInfo() throws Exception {
return userService.getAllUsers();
} @RequestMapping(value = "/getSingleUser", method = RequestMethod.GET)
public UserBean getSingleUser(@Param("id") String id) throws Exception {
//return userService.getSingleUsers(id);
return userService.getUserInfo(id);
} @RequestMapping(value = "/getOneUserInfo", method = RequestMethod.GET)
public UserBean getSingleUser(@Param("id") String id, @Param("name") String name) throws Exception {
return userService.getOneUserInfo(id, name);
} @RequestMapping(value = "/getUserCount", method = RequestMethod.GET)
public int getUserCountForAllUsers() throws Exception {
return userService.getUsersCount();
} @RequestMapping(value = "updateUser")
public void updateUserInfo(){
userService.updateUserInfo();
} @RequestMapping(value = "/addUsers", method = RequestMethod.GET)
public void addUsers(List<UserBean> list) throws Exception {
List<UserBean> users = new ArrayList<>();
UserBean user1 = new UserBean();
user1.setAge(28);
user1.setId(12);
user1.setName("Mr One");
UserBean user2 = new UserBean();
user2.setAge(31);
user2.setId(11);
user2.setName("Mr Two");
users.add(user1);
users.add(user2);
userService.addUsers(list);
} @RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
public void deleteUser(@Param("id") String id, @Param("name")String name) throws Exception {
userService.deleteUser(id, name);
}
}

  3) 数据库操作类UserDAO:(定义为接口方式,serviceImpl用来实现具体的增删改查操作,可以使用Mybatis映射器方式直接拼写SQL(注释掉的@Select("")等), 也可以定义UserMapper.xml文件用来通过配置文件生成SQL)

package com.test.dao;

import com.test.pojo.UserBean;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import java.util.List; public interface UserDAO { List<UserBean> selectAllUser() throws Exception; //@Select("select * from user where id=#{id}") ---映射器方式:入参需要改为String类型
UserBean selectSingleUser(@Param("id") Integer id); //@Select("select * from user where id=#{id} and name=#{name}") ---映射器方式:入参需要改为String类型
UserBean selectOneUserInfo(@Param("id") Integer id, @Param("name") String name); int countUsers(); void insertUser(@Param("list") List<UserBean> list); // @Delete("delete from user where id=#{id}")
void deleteUser(@Param("id") Integer id, @Param("name") String name) throws Exception; void updateUserInfo(@Param("id")Integer id, @Param("user") UserBean user); @Select("select * from user where id=#{id}")
UserBean getUserInfo(@Param("id") String id);
}

  4) UserService(数据库操作接口类)

package com.test.service;

import com.test.pojo.UserBean;

import java.util.List;

public interface UserService {

    List<UserBean> getAllUsers() throws Exception;

    void addUsers(List<UserBean> list);

    void deleteUser(String id, String name) throws Exception;

    UserBean getSingleUsers(String id);

    int getUsersCount();

    UserBean getOneUserInfo(String id, String name);

    void updateUserInfo();

    UserBean getUserInfo(String id);
} 

  5)UserServiceImpl(UserService的实现类)

package com.test.service.impl;

import com.test.dao.UserDAO;
import com.test.pojo.UserBean;
import com.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; @Service("user")
public class UserServiceImpl implements UserService { @Autowired(required = false)
UserDAO userDAO; @Override
public List<UserBean> getAllUsers() throws Exception {
return userDAO.selectAllUser();
} @Override
public UserBean getSingleUsers(String id) {
return userDAO.selectSingleUser(Integer.parseInt(id));
} @Override
public int getUsersCount() {
return userDAO.countUsers();
} @Override
public void addUsers(List<UserBean> list) {
userDAO.insertUser(list);
} @Override
public void deleteUser(String id, String name) throws Exception {
userDAO.deleteUser(Integer.parseInt(id), name);
} @Override
public UserBean getOneUserInfo(String id, String name) {
if(id != null && !"".equals(id)){
if(name != null){
return userDAO.selectOneUserInfo(Integer.parseInt(id), name);
}else{
return userDAO.selectOneUserInfo(Integer.parseInt(id), null);
}
}else {
return userDAO.selectOneUserInfo(null, name);
}
} @Override
public void updateUserInfo() {
UserBean user = new UserBean();
user.setId(3);
user.setAge(33);
user.setName("haha");
userDAO.updateUserInfo(1, user);
} @Override
public UserBean getUserInfo(String id) {
return userDAO.getUserInfo(id);
}
}

四、客户端文件:

  本例只使用了静态页面作为初始化加载的界面展示,路径为:web/page/index.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>This is a test Page for Spring Test</h1> </body>
</html> 

  本例中的返回信息使用了Alibaba的fastJson作为返回对象(未使用视图解析器),故界面ajax请求返回数据可根据返回值作为数据填充,具体的界面设计需要自由发挥。

五、 Tomcat配置:

  两种方式查看:

  1. 配置Tomcat文件:

    1)将web文件夹放入 tomcat 解压包的 apache-tomcat-7.0.54\webapps\ 目录下;

    2) 将编译后的jar包放入 WEB-INF 目录下的lib文件夹下

    3)启动Tomcat

  2. IntelliJ 集成了Tomcat 插件,可以直接启动,具体配置路径如下:
    Run--->Edit Configurations--->"+"--->Tomcat Server--->Local 或者 Remote选项配置
    (注意Deployment Tab页下要将对应的war包导入)
    然后启动即可

 

基于SpringMVC+Mybatis搭建简单的前后台交互系统的更多相关文章

  1. 基于tomcat+springMVC搭建基本的前后台交互系统

    一.摘要 1.所需软件列表: 1) tomcat :  apache-tomcat-7.0.54  服务端容器 2) Intellij: Intellij IDEA 14.0.3         开发 ...

  2. JAVA配置&注解方式搭建简单的SpringMVC前后台交互系统

    前面两篇文章介绍了 基于XML方式搭建SpringMVC前后台交互系统的方法,博文链接如下: http://www.cnblogs.com/hunterCecil/p/8252060.html htt ...

  3. 基于SpringBoot+MyBatis实现一套电商系统

    项目介绍 mall项目是一套电商系统,包括前台商城系统及后台管理系统,基于SpringBoot+MyBatis实现. 前台商城系统包含首页门户.商品推荐.商品搜索.商品展示.购物车.订单流程.会员中心 ...

  4. window 平台搭建简单的直播点播系统

    Windows平台如何搭建简单的直播系统前文已经有介绍,今天介绍下如何搭建简单的点播系统. 同样还是利用crtmpServer,crtmpServer可以从github中下载,可以从群里下载(群里有修 ...

  5. java maven、springmvc、mybatis 搭建简单Web项目学习笔记

    前言: 空余的时间,学学 Java,没准哪天用的到: 环境搭建折腾了好几天,总算搞顺了,也做个学习笔记,以防后面会忘记: 一.安装文件及介绍 JDK:jdk1.8.0 77 eclipse-maven ...

  6. 大型运输行业实战_day03_1_基于intellij idea的非maven spring+springMVC+mybatis搭建

    1.搭建标准web项目结构 搭建完成后的项目结构如图 1.创建普通web项目(略) 2.在lib中添加jar包 3.在resources中添加spring-config.xml主配置文件 <?x ...

  7. Android+Struts2实现简单的前后台交互--Android网络编程

    1.下面测试截图,基本过程就是:点击按钮向服务器端发送请求,后台收到请求后给出返回的数据,前台只需要显示服务端数据就可以了.例子很简单能但引发很多思考,博主学了杂七杂八的,这又在来想杂学Android ...

  8. maven+springMVC+mybatis 搭建过程

    1.创建maven web 项目 maven 创建web应用命令: mvn archetype:generate -DgroupId=[com.rom]包名 -DartifactId=[cpsrom] ...

  9. Spring+SpringMVC+Mybatis搭建的网站的处理流程总结

    最近学习了如何使用SSM框架搭建网站,以前没用过框架,第一次使用,总结一下自己对框架处理流程的理解

随机推荐

  1. Flask笔记

    # -*- coding: utf-8 -*- from flask import Flask,render_template,request,redirect,session,url_for imp ...

  2. ssm maven spring AOP读写分离

    ssm maven spring AOP读写分离 总体流程 配置最开始写在pom.xml文件,解析到数据库配置文件,再解析到spring配置文件. 自定义注解DataSource:通过这个注解并且在s ...

  3. 51 Nod 1008 N的阶乘 mod P【Java大数乱搞】

    1008 N的阶乘 mod P 基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 输入N和P(P为质数),求N! Mod P = ? (Mod 就是求模 %)   例如:n ...

  4. hdu_4463(最小生成树)

    hdu_4463(最小生成树) 标签: 并查集 题目链接 题意: 求一个必须包含一条路径的最小生成树 题解: 把那条边初始化成0 保证这条边一定会被选 #include<cstdio> # ...

  5. Treap(树堆)

    treap是排序二叉树的一种改进,因为排序二叉树有可能会造成链状结构的时候复杂度变成O(n^2)所以通过随机一个优先级的方法来维持每次让优先级最大的作为树根,然后形成一个满足: A. 节点中的key满 ...

  6. 关于vue的使用计算属性VS使用计算方法的问题

    在vue中需要做一些计算时使用计算属性和调用methods方法都可以达到相同的效果,那么这两种使用方式的区别在哪里: <div id="example"> <p& ...

  7. YUM常用命令介绍

    http://www.cnblogs.com/lostyue/archive/2012/05/06/2485653.html 1.列出所有可更新的软件清单 命令:yum check-update 2. ...

  8. ThinkPHP配置文件的加载

    分类: thinkphp(39) 版权声明:本文为博主原创文章,未经博主允许不得转载. 惯例配置->应用配置->模式配置->调试配置->状态配置->模块配置->扩展 ...

  9. 有经验JAVA程序员如何提升自己?

    作为一个具有一到五年开发经验程序员,需要学习内容很多: JVM/分布式/高并发/性能优化/Spring MVC/Spring Boot/Spring Cloud/MyBatis/Netty源码分析等等 ...

  10. Angular CLI: 发布到 GitHub Pages

    发布 Angular 应用的简单方式是使用 GitHub Pages. 首先需要创建一个 GitHub 账号,随后,为您的项目创建一个仓库.记下 GitHub 中的用户名和项目名称. 例如,我的 Gi ...