每一秒钟的时间都值得铭记

0%

SSM框架整合

SSM框架

所谓SSM,即SpringMVC+Spring+Mybatis三个框架的合称,也是目前国内最为流行的企业级开发框架。

虽然目前国内的趋势是SpringBoot,但是SpringBoot只不过是将开发简单化了,使用约定大于配置的规则,对框架进行了自动配置,省略了SSM框架需要手动配置的麻烦。
所以,SpringBoot的底层依然还是Spring框架的那一套模式,那么我们学习SSM框架,利用Spring来整合SpringMVC和Mybatis框架依然还是有必要的,这可以让我们对SpringBoot有更深的了解。

搭建项目环境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.hrp</groupId>
<artifactId>my_first_ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<!--注意,这里将项目打成一个war包-->
<packaging>war</packaging>

<!--统一管理版本-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.2.RELEASE</spring.version>
<mybatis.version>3.4.6</mybatis.version>
<mybatis.spring.version>1.3.2</mybatis.spring.version>
<mysql.version>5.1.32</mysql.version>
<druid.version>1.0.9</druid.version>
<slf4j.version>1.6.6</slf4j.version>
<lombox.version>1.16.22</lombox.version>
<jstl.version>1.2</jstl.version>
<jsp-api.version>2.0</jsp-api.version>
</properties>

<dependencies>
<!--springmvc的依赖,这个依赖同时也依赖着spring的其他集合核心依赖,所以引入了这个依赖,就可以不用引入spring的那几个核心依赖了-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--springjdbc的依赖,不在上面那个依赖的依赖范围,事务管理必须要的依赖jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring整合aspects框架,后面基于xml配置的声明式事务管理需要用到-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Mybatis的依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--spring整合Mybatis的依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!-- MySql的驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- druid连接池,阿里开源项目 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- 日志处理 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--Lombox插件依赖,主要是用于自动生成getter和setter方法,没有也没关系,自己写getter和setter方法就可以了-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombox.version}</version>
<scope>provided</scope>
</dependency>
<!--jstl表达式的依赖-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- JSP相关的依赖,依赖范围是provided,只在编译和测试时使用 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>

<build>
<!--Maven插件-->
<plugins>
<!-- 编译环境,JDK8-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 运行环境,tomcat7-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8080</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>

编写配置文件

log4j配置文件

1
2
3
4
5
6
# Global logging configuration
log4j.rootLogger=INFO, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

jdbc.properties,配置数据库连接属性

1
2
3
4
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_database08
jdbc.username=root
jdbc.password=admin

applicationContext.xml配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

<!--在application.xml文件中引入jdbc.properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>

<!--配置dataSource,属性为引入jdbc.properties内的属性-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

<!--配置sqlSessionFactory,其中注入dataSource和实体类别名包扫描目录-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--实体类别名包扫描,所有的实体类放在com.hrp.domain包下-->
<property name="typeAliasesPackage" value="com.hrp.domain"/>
</bean>

<!--配置mybatis和spring整合之后的持久层扫描-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--所有的持久层类放在com.hrp.dao包下-->
<property name="basePackage" value="com.hrp.dao"/>
</bean>

<!--Service层的配置,扫描service包下的所有注解,业务层放在com.hrp.service包下-->
<context:component-scan base-package="com.hrp.service"/>

<!--spring提供的事务管理器,注入dataSource-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

<!--声明式事务管理,事务的通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--事务的传播行为,所有的保存方法使用save打头-->
<tx:method name="save*" propagation="REQUIRED" />
<!--所有的删除方法使用delete打头-->
<tx:method name="delete*" propagation="REQUIRED" />
<!--所有的更新方法使用update打头-->
<tx:method name="update*" propagation="REQUIRED" />
<!--所有的查询方法使用find打头-->
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>

<!--配置切面,service.impl包下的所有类所有方法都进行切面拦截-->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.hrp.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
</aop:config>

</beans>

springmvc.xml配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?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-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<!-- 配置Controller注解扫描,所有的控制层放在com.hrp.controller下-->
<context:component-scan base-package="com.hrp.controller" />

<!--处理器映射器,处理器适配器-->
<mvc:annotation-driven/>

<!-- 配置视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/" />
<!--后缀-->
<property name="suffix" value=".jsp" />
</bean>

<!--释放静态资源-->
<mvc:default-servlet-handler/>

</beans>

web.xml配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?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>Interview</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<!--编码过滤器 -->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 配置spring核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 重新指定spring配置文件的路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<!-- 配置springmvc的核心servlet -->
<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.xml</param-value>
</init-param>
<!-- 配置springmvc什么时候启动,参数必须为整数 -->
<!-- 如果为0或者大于0,则springMVC随着容器启动而启动 -->
<!-- 如果小于0,则在第一次请求进来的时候启动 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 所有的请求都进入springMVC -->
<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

编写代码

创建数据库

1
2
3
4
5
6
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(11) DEFAULT NULL,
`password` varchar(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;

编写实体类

1
2
3
4
5
6
7
8
9
10
11
12
 import lombok.Data;

/**
* 实体类User
* @author hrp
*/
@Data
public class User {
private String id;
private String name;
private String password;
}

编写持久层,业务层和Web层

  • 持久层

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    public interface UserDao {

    /**
    * 查找所有用户
    * @return
    * @throws Exception
    */
    @Select("select * from tb_user")
    List<User> findAll() throws Exception;

    /**
    * 根据id删除用户
    * @param id
    * @throws Exception
    */
    @Delete("delete from tb_user where id = #{id}")
    void deleteUser(Integer id) throws Exception;

    /**
    * 保存用户
    * @param user
    * @throws Exception
    */
    @Insert("insert into tb_user(name,password) values(#{name},#{password})")
    void saveUser(User user) throws Exception;

    }
  • 业务层

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    public interface UserService {

    /**
    * 查找所有用户
    * @return
    * @throws Exception
    */
    List<User> findAll() throws Exception;

    /**
    * 根据id删除用户
    * @param id
    * @throws Exception
    */
    void deleteUser(Integer id) throws Exception;


    /**
    * 保存用户
    * @param user
    * @throws Exception
    */
    void save(User user) throws Exception;

    }
  • 业务层接口实现

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    @Service
    public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> findAll() throws Exception {
    return userDao.findAll();
    }

    @Override
    public void deleteUser(Integer id) throws Exception {
    userDao.deleteUser(id);
    }

    @Override
    public void save(User user) throws Exception {
    userDao.saveUser(user);
    }
    }
  • Web控制层

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    @Controller
    @RequestMapping("user")
    public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("list")
    public String findAll(Model model) throws Exception{
    List<User> list = userService.findAll();
    model.addAttribute("list",list);
    return "list";
    }

    @RequestMapping("delete/{id}")
    public String deleteUser(@PathVariable Integer id) throws Exception{
    userService.deleteUser(id);
    return "forward:/user/list";
    }

    @RequestMapping("save")
    public String save(User user) throws Exception {
    userService.save(user);
    return "forward:/user/list";
    }

    }

测试功能

写到这里,Spring整合MVC和Mybatis就以及完成了,接下来就是测试了。
使用Maven集成的Tomcat插件启动项目,访问localhost:8080
如果你在webapp目录下有index页面,就会直接跳转到inex页面中,如果没有,也可以直接访问Controller暴露出来的接口。
http://localhost:8080/user/list
记得在WEB-INF下创建一个名为jsp的文件夹,将所有的jsp页面放在该文件夹下。

例如:list.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>所有用户</title>
</head>
<body>
<h1>所有用户</h1>
<table>
<tr>
<td>ID</td>
<td>用户名</td>
<td>密码</td>
</tr>
<c:forEach var="user" items="${list}">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.password}</td>
<td><a href="/user/delete/${user.id}">删除</a></td>
</tr>
</c:forEach>
</table>

</body>
</html>
坚持原创技术分享,您的支持将鼓励我继续创作!
-------------这是我的底线^_^-------------