SSM整合开发

SSM:SpringMVC + Spring +MyBatis

SpringMVC:视图层,用于接收页面请求,显示处理结果
Spring:业务层,管理service,dao,工具类对象
Mybatis:持久层,访问数据库

用户发起请求—>SpringMVC接收—>Spring中调用的Service对象处理事务—>MyBatis处理数据

1、整合的思路

在进行整合时,有两个容器对象
1、SpringMVC容器,管理Controller控制器对象
2、Spring容器,管理Service,Dao,工具类对象
我们要把使用的对象交给合适的容器去创建,管理。
把Controller还有web开发相关对象交给SpringMVC容器,将这些web使用的对象写在springmvc配置文件中。
把Service,Dao对象定义在Spring的配置文件中,让Spring管理这些对象。

两个容器之间的关系:
SpringMVC容器是Spring的子容器,类似于Java中的子父类关系——子类可以访问父类的数据。
即在子容器SpringMVC中的Controller可以访问父容器Spring中的Service对象,就可以实现Controller使用Service对象。

2、整合的步骤

使用之前创建好的mybatis数据库,使用student表

1、创建maven web项目

2、加入依赖

springmvc,spring,mybatis三个框架的依赖,jackson依赖,mysql驱动,druid连接池,jsp,servlet依赖

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
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- jsp依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
<!--springmvc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<!--mysql-->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
</dependencies>

<build>
<resources>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml 文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>

3、写web.xml

1、注册中央处理器DispatcherServlet,
目的:1、创建springmvc容器对象,才能创建Controller对象;2、创建的是Servlet,才能接收用户的请求。

2、注册监听器ContextLoaderListener,
目的:创建spring容器对象,才能创建service,dao等对象

3、注册字符集过滤器CharacterEncodingFilter,
目的:解决post请求乱码

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
<?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_4_0.xsd"
version="4.0">

<!-- 注册中央调度器 -->
<servlet>
<servlet-name>myweb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myweb</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<!-- 注册监听器 用于创建Spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/application.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!--注册字符集过滤器-->
<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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

4、创建包

创建controller、service、dao、bean包

5、写springmvc,spring,mybatis的配置文件

1、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
<?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.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--springmvc配置文件,声明 controller和它相关的对象-->
<context:component-scan base-package="com.zyz.controller" />

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

<!--注解驱动-->
<mvc:annotation-driven/>
</beans>

2、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
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

<!-- 将数据库配置文件写入单独的文件中 -->
<context:property-placeholder location="classpath:conf/jdbc.properties"/>
<!--声明数据源 用于连接数据库-->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
</bean>

<!--声明mybatis中的SqlSessionFactoryBean 用于创建SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- set注入,把数据库连接池赋值给dateSource属性-->
<property name="dataSource" ref="myDataSource"/>
<!-- mybatis主配置文件的位置-->
<property name="configLocation" value="classpath:conf/mybatisConfig.xml"/>
</bean>

<!-- 声明Dao类
MapperScannerConfigurer:在内部调用getMapper()生成每一个接口的dao代理对象
创建好的dao对象放在spring容器中,默认名称为 接口名首字母小写-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.zyz.dao"/>
</bean>

<!-- 声明service的注解@Service所在的包名位置 -->
<context:component-scan base-package="com.zyz.service"/>

<!-- 事务配置:注解的配置或aspectj的配置 -->
</beans>

3、mybatisConfig.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
<!-- 注册映射文件 -->
<mappers>
<package name="com.zyz.dao"/>
</mappers>

</configuration>

4、jdbc.properties

1
2
3
4
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=2824199842
jdbc.maxActive=20

6、编写各个包的代码

bean实体类

dao接口和mapper文件

1
2
3
4
5
6
7
8
9
10
11
package com.zyz.dao;

import com.zyz.bean.Employee;

import java.util.List;

public interface EmployeeDao {

public int insertEmp(Employee employee);
List<Employee> listAllEmps();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
<?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.zyz.dao.EmployeeDao">
<select id="listAllEmps" resultType="com.zyz.bean.Employee">
select name,gender,email,dept_id deptId from employee order by id asc
</select>

<insert id="insertEmp">
insert into employee(name,gender,email,dept_id) values (#{name},#{gender},#{email},#{deptId})
</insert>
</mapper>

service及其实现类

1
2
3
4
public interface EmployeeService {
int addEmp(Employee employee);
List<Employee> listAllEmps();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Service
public class EmployeeServiceImpl implements EmployeeService {

// 引用类型自动注入@Autowired,@Resource dao对象就在Spring容器中
@Resource
private EmployeeDao employeeDao;
@Override
public int addEmp(Employee employee) {
return employeeDao.insertEmp(employee);
}

@Override
public List<Employee> listAllEmps() {
return employeeDao.listAllEmps();
}
}

controller

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
@Controller
@RequestMapping("/employee")
public class EmployeeController {

@Resource
private EmployeeService employeeService;

// 员工注册
@RequestMapping("/addEmployee.do")
public ModelAndView addStudent(Employee employee){
ModelAndView modelAndView = new ModelAndView();
String tips = "注册失败";
// 调用service
int num = employeeService.addEmp(employee);
if(num>0){
// 注册成功
tips="注册成功!";
}
// 添加数据
modelAndView.addObject("tips",tips);
// 指定结果页面
modelAndView.setViewName("result");
return modelAndView;
}

// 员工查询
@RequestMapping("/listAllEmps.do")
@ResponseBody
public List<Employee> listAllEmp(){
return employeeService.listAllEmps();
}
}

7、编写页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%String basePath = request.getContextPath()+"/";%>
<html>
<head>
<title>首页</title>
<base href="<%=basePath%>"/>

</head>
<body>
<div align="center">
<img src="images/yy.jpg" style="width: 200px;height: 200px">
<table>
<tr>
<td><a href="addEmployee.jsp">注册员工</a></td>
</tr>
<tr>
<td><a href="listAllEmployee.jsp">浏览员工</a></td>
</tr>
</table>
</div>
</body>
</html>
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
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%String basePath = request.getContextPath() + "/";%>
<html>
<head>
<title>注册员工</title>
<base href="<%=basePath%>"/>
</head>
<body>
<div align="center">
<form action="employee/addEmployee.do" method="post">
<table>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="radio" name="gender" value="1"/>&nbsp;&nbsp;&nbsp;
<input type="radio" name="gender" value="0"/>
</td>
</tr>
<tr>
<td>电子邮箱:</td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td>部门编号:</td>
<td><input type="number" name="deptId"/></td>
</tr>
<tr>
<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
<td><input type="submit" value="注册"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
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
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%String basePath = request.getContextPath() + "/";%>
<html>
<head>
<title>查询所有员工</title>
<base href="<%=basePath%>"/>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
$(function () {
// 当前页面dom对象加载后,立即执行
loadEmpData();
})
function loadEmpData() {
$.ajax({
url: "employee/listAllEmps.do",
type: "get",
dataType: "json",
success: function (data) {
// alert(data);
// 清除旧数据
$("#info").html("");
$.each(data, function (k, v) {
$("#info").append("<tr>")
.append("<td>" + v.name + "</td>")
.append("<td>" + v.gender + "</td>")
.append("<td>" + v.email + "</td>")
.append("<td>" + v.deptId + "</td>")
})
}
})
}
</script>
</head>
<body>
<div align="center">
<table border="1" cellspacing="0">
<tr>
<th>姓名</th>
<th>性别</th>
<th>电子邮箱</th>
<th>部门编号</th>
</tr>
<tr>
<tbody id="info"></tbody>
</tr>
</table>
</div>
</body>
</html>

项目整体结构: