源码:
链接: https://pan.baidu.com/s/1jIQqOaq
密码: f254
其中ssm是注解方式,ssm2是xml方式
1、Maven构建一个maven-archetype-webapp项目,在pom.xml中添加相关的jar包依赖
<!-- mybatis依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!-- MySQL jdbc驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> </dependency> <!-- spring mvc相关依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!-- spring jdbc依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!-- spring事务 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!-- jackson依赖 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.3</version> </dependency> <!-- mybatis-spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- c3p0数据连接池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency>
2、在resources目录下添加springmvc-config.xml文件,并进行配置
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 包扫描 --> <context:component-scan base-package="com.app.*" /> <!-- 注解驱动 --> <mvc:annotation-driven /> <!-- html文件处理 --> <mvc:resources mapping="/*.html" location="/" /> <!-- 视图解析 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
3、在resources目录添加db.properties文件,配置数据库连接属性
dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://127.0.0.1:3306/ssm
dataSource.user=root
dataSource.password=root
dataSource.maxPoolSize=20
dataSource.maxIdleTime = 1000
dataSource.minPoolSize=5
dataSource.initialPoolSize=5
4、在resources目录下添加applicationsContext.xml文件,并进行配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mybatis="http://mybatis.org/schema/mybatis-spring" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd "> <!-- mybatis:scan会将com.app.mapper包里的所有接口当作mapper配置,之后可以自动引入mapper类 --> <mybatis:scan base-package="com.app.mapper" /> <!-- 扫描com.app包下面的java文件,有Spring的相关注解的类,则把这些类注册为Spring的bean --> <context:component-scan base-package="com.app" /> <!-- 使用PropertyOverrideConfigurer后处理器加载数据源参数 --> <context:property-override location="classpath:db.properties" /> <!-- 配置c3p0数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" /> <!-- 配置SqlSessionFactory,org.mybatis.spring.SqlSessionFactoryBean是Mybatis社区开发用于整合Spring的bean --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" /> <!-- JDBC事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" /> <!-- 启用支持annotation注解方式事务管理 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
5、配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>Archetype Created Web Application</display-name> <!-- 配置spring核心监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- contextConfigLocation参数用来指定Spring的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext*.xml</param-value> </context-param> <!-- 定义Spring MVC的前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 让Spring MVC的前端控制器拦截所有请求 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 编码过滤器 --> <filter> <filter-name>characterEncodingFilter</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> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
到此基本的环境算搭建完毕,下面步骤为测试环境是否可用,如只是参考环境搭建,下面步骤可忽略。
6、创建数据库与表
CREATE DATABASE ssm; USE ssm; CREATE TABLE `tb_user` ( `id` INT (11) NOT NULL AUTO_INCREMENT, `userName` VARCHAR (18) DEFAULT NULL, `birth` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) );
7、创建一个映射数据表的User实体类
package com.app.entity; import java.io.Serializable; import java.util.Date; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonFormat; @SuppressWarnings("serial") public class User implements Serializable { private Integer id; private String userName; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birth; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+08") public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } }
8、创建一个操作tb_user表的UserMapper接口(注意是接口),添加两个方法用于后面的测试
package com.app.mapper; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Select; import com.app.entity.User; public interface UserMapper { @Select("select * from tb_user where id = #{id}") User findUserById(Integer id); @Insert("insert into tb_user(userName, birth) values(#{userName}, #{birth})") @Options(useGeneratedKeys = true, keyProperty = "id") public Integer saveUser(User user); }
9、Service层的实现
UserService接口
package com.app.servcie; import com.app.entity.User; public interface UserService { User findUserById(Integer id); Integer saveUser(User user); }
UserService接口的实现类UserServiceImp
package com.app.servcie; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.app.entity.User; import com.app.mapper.UserMapper; @Service(value = "userService") public class UserServiceImp implements UserService { @Autowired private UserMapper userMapper; @Override public Integer saveUser(User user) { return userMapper.saveUser(user); } @Override public User findUserById(Integer id) { return userMapper.findUserById(id); } }
10、Controller层的实现(将数据添加到数据库,并将添加后的数据信息返回到客户端显示)
package com.app.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.app.entity.User; import com.app.servcie.UserService; @Controller public class UserController { @Autowired private UserService userService; @RequestMapping("/insertUser") @ResponseBody public User insertUser(User user) { userService.saveUser(user); User resultUser = userService.findUserById(user.getId()); return resultUser; } }
11、在webapp根目录下创建一个index.jsp(一般默认已经有了),添加如下代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>添加用户</title> <style type="text/css"> #content { text-align: center; } </style> </head> <body> <div id="content"> <form method="post" action="insertUser"> 姓名:<input type="text" id="userName" name="userName"><br> 生日:<input type="text" id="birth" name="birth"><br> <input type="submit" value="确定"> </form> </div> </body> </html>
12、运行部署项目进行测试
在index.jsp页面填写相关的数据
执行后的效果
被添加进数据库中的数据
-------------------- 基于XML方式 --------------------
上面测试部分使用的注解方式,如果要使用xml方式,有三个地方需要修改一下。
1、applicationContext.xml文件里面的sqlSessionFactory下需要添加*Mapper.xml文件的路径映射(下面黄色背景处)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mybatis="http://mybatis.org/schema/mybatis-spring" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd "> <!-- mybatis:scan会将com.app.mapper包里的所有接口当作mapper配置,之后可以自动引入mapper类 --> <mybatis:scan base-package="com.app.mapper" /> <!-- 扫描com.app包下面的java文件,有Spring的相关注解的类,则把这些类注册为Spring的bean --> <context:component-scan base-package="com.app" /> <!-- 使用PropertyOverrideConfigurer后处理器加载数据源参数 --> <context:property-override location="classpath:db.properties" /> <!-- 配置c3p0数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" /> <!-- 配置SqlSessionFactory,org.mybatis.spring.SqlSessionFactoryBean是Mybatis社区开发用于整合Spring的bean --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource"> <property name="mapperLocations"> <list> <value>classpath*:com/app/mapper/*Mapper.xml</value> </list> </property> </bean> <!-- JDBC事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" /> <!-- 启用支持annotation注解方式事务管理 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
2、去掉UserMapper.java接口中的注解
package com.app.mapper; import com.app.entity.User; public interface UserMapper { User findUserById(Integer id); public Integer saveUser(User user); }
3、添加SQL Mapper的UserMapper.xml文件,并添加相应的SQL语句映射(其实跟上面的注解方式差不多,只是SQL跟接口方法分开了而已)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.app.mapper.UserMapper"> <select id="findUserById" parameterType="int" resultType="com.app.entity.User"> select * from tb_user where id = #{id} </select> <insert id="saveUser" parameterType="com.app.entity.User"> insert into tb_user(userName, birth) values(#{userName}, #{birth}) <selectKey keyColumn="id" resultType="int" keyProperty="id" order="AFTER"> select LAST_INSERT_ID() </selectKey> </insert> </mapper>
其他地方的配置写法跟注解方式一样,不用修改。
-------------------- 额外内容 --------------------
分页配置参考(接本文档):