SSM整合CRUD

配置Pom.xml文件

[什么是servlet? - niceyoo - 博客园 (cnblogs.com)](https://www.cnblogs.com/niceyoo/p/10617604.html#:~:text=Java Servlet API 是Servlet容器 (tomcat)和servlet之间的接口,它定义了Serlvet 的各种方法,还定义了 Servlet,容器传送给 Servlet 的对象类,其中最重要的就是 ServletRequest 和 ServletResponse 。)

需要的配置

  1. Spring
  2. SpringMVC
  3. Mybatis
  4. Spring适配Mybaits
  5. 阿里druid连接池
  6. jdbc
  7. 视图解析器包
  8. spring-jdbc事务控制的包
  9. 使用Aspectj的jar包
  10. servlet-api的包
  11. 单元测试包
  12. 除此之外,我们还需要将dao.xml文件可编译到target文件中

配置

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
125
126
127
<?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>org.example</groupId>
<artifactId>SSM-Project</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<name>SSM-Project Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.19</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.19</version>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>

<!--阿里巴巴数据库连接池依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.9</version>
</dependency>

<!-- Spring5和Thymeleaf整合包 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.15.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.19</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.19</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.1</version>
</dependency>

<!-- ServletAPI -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<!--使得不在resoures文件下的依赖也可以被编译-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<include>**/*.html</include>
</includes>
</resource>
</resources>
</build>

</project>

测试Spring环境

创建类

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
package com.zss.pojo;

/**
* @author zss
*/
public class Employee {
private Integer empId;
private String empName;
private byte gender;
private String email;
private Integer dId;

public Employee() {
}

public Employee(Integer empId, String empName, byte gender, String email, Integer dId) {
this.empId = empId;
this.empName = empName;
this.gender = gender;
this.email = email;
this.dId = dId;
}

public Integer getEmpId() {
return empId;
}

public void setEmpId(Integer empId) {
this.empId = empId;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public byte getGender() {
return gender;
}

public void setGender(byte gender) {
this.gender = gender;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public Integer getdId() {
return dId;
}

public void setdId(Integer dId) {
this.dId = dId;
}
}

设置dao

1
2
3
public interface EmployeeDao {
public List<Employee> getEmployees();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
import com.zss.dao.EmployeeDao;
import com.zss.pojo.Employee;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public class EmployeeDaoImpl implements EmployeeDao {
@Override
public List<Employee> getEmployees() {
System.out.println("执行dao");
return null;
}
}

设置Service

1
2
3
public interface EmployeeService {
public List<Employee> getEmployees();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.zss.service.impl;

import com.zss.dao.EmployeeDao;
import com.zss.pojo.Employee;
import com.zss.service.EmployeeService;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class EmployeeServiceImpl implements EmployeeService {
private EmployeeDao employeeDao;

public void setEmployeeDao(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
}

@Override
public List<Employee> getEmployees() {

return employeeDao.getEmployees();
}
}

配置Spring容器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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">

<!--扫描spring加载包-->
<context:component-scan base-package="com.zss">
<!--不扫描Controller-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<bean id="employeeService" class="com.zss.service.impl.EmployeeServiceImpl">
<property name="employeeDao" ref="employeeDao"/>
</bean>

<bean id="employeeDao" class="com.zss.dao.impl.EmployeeDaoImpl"/>
</beans>

测试

1
2
3
4
5
6
7
8
9
public class TestSpring {
@Test
public void test01(){
//加载spring配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
EmployeeService employeeService=(EmployeeService) applicationContext.getBean("employeeService");
List<Employee> employeeList= employeeService.getEmployees();
}
}

image-20220511110649142

测试springmvc环境

设置controller

1
2
3
public interface EmployeeController {
public ModelAndView showIndex();
}
1
2
3
4
5
6
7
8
9
10
@Controller
public class EmployeeControllerImpl implements EmployeeController {
@Override
@RequestMapping("/begin")
public ModelAndView showIndex() {
ModelAndView modelAndView=new ModelAndView();
modelAndView.setViewName("index");
return modelAndView;
}
}

配置Springmvc文件

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
<?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">

<!--扫描controller的组件-->
<context:component-scan base-package="com.zss">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!--配置视图解析器-->
<!--配置视图解析器-->
<!-- 配置Thymeleaf视图解析器 -->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<!--视图解析器优先级-->
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">

<!-- 设置视图前缀 -->
<property name="prefix" value="/WEB-INF/templates/"/>
<!-- 设置视图后缀 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" />
</bean>
</property>
</bean>
</property>
</bean>

<!--如果浏览器发送的信息,dispatcherservlet处理不了,则交给defaultservlet处理,开启对静态资源的访问和默认驱动-->
<mvc:default-servlet-handler/>
<!--开启注解驱动,要这两个标签同时使用-->
<mvc:annotation-driven/>

</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
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>

<!--控制中文乱码-->
<!--设置过滤器,控制编码-->
<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>
<!--//设置响应的编码是否也启用encoding-->
<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>

<!--设置中央控制器-->
<!--对所有的页面进行控制-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载springmvc配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

测试

配置tomcat,打开相应页面

image-20220511110935149

Spring整合Springmvc

配置监听器

监听器可以在第一时间告诉我们项目已经启动,可以加载spring容器

1
2
3
4
5
6
7
8
9
<!--配置监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置监听器加载文件的指定路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

测试

添加依赖

1
2
3
<bean id="employeeController" class="com.zss.controller.impl.EmployeeControllerImpl">
<property name="employeeService" ref="employeeService"/>
</bean>
1
2
3
4
5
6
7
8
@Override
@RequestMapping("/begin")
public ModelAndView showIndex() {
ModelAndView modelAndView=new ModelAndView();
employeeService.getEmployees();
modelAndView.setViewName("index");
return modelAndView;
}

测试成功

配置mybatis

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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>
<!--设置日志-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--设置包名-->
<typeAliases>
<!--实体类所在的包名称-->
<package name="com.zss.pojo"/>
</typeAliases>

<!--该包下面的所有包配置文件-->
<mappers>
<package name="com.zss.dao"/>
</mappers>
</configuration>

书写出执行的语句,设置映射对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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.zss.dao.EmployeeDao">
<resultMap id="employeeMap" type="com.zss.pojo.Employee">
<result column="emp_id" property="empId"/>
<result column="emp_name" property="empName"/>
<result column="dept_name" property="deptName"/>
</resultMap>
<select id="getEmployees" resultMap="employeeMap">
SELECT emp_id,emp_name,gender,email,td.dept_name FROM tb_emp JOIN tb_dept td ON td.dept_id = tb_emp.d_id order by emp_id;
</select>
</mapper>

声明数据源创建对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<context:property-placeholder location="classpath:mysqldb.properties"/>
<!--声明数据源对象-->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<!--使用set注入提供配置信息-->
<property name="url" value="${url}"/>
<property name="username" value="root"/>
<property name="password" value="200101"/>
</bean>
<!--声明sqlSessionFactoryBean类,创建sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--设置植入数据库的连接池-->
<property name="dataSource" ref="myDataSource"/>
<!--找到mybaits主配置文件的位置,如果要在主配置文件中加入其他文件的配置,需要使用classpath,赋值需要使用value-->
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>

<!--创建dao,MapperScannerConfigurer这个类在内部调用get-mapper生成每个接口的代理对象,同时会扫描包名,每一个接口执行
getMapper的方法,得到dao对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.zss.dao"/>
</bean>

测试并且映射页面

添加事务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!--启用事务管理器的事务处理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--指定对哪一个事务进行管理-->
<property name="dataSource" ref="myDataSource"/>
</bean>
<!--声明业务方法事务属性,id表示这一段的配置内容-->
<tx:advice id="myAdvice" transaction-manager="transactionManager">
<!--<tx:attributes>配置事务属性,name配置方法名称,当然也可以使用通配符,也可以在这里配置隔离级别等信息-->
<tx:attributes>
<tx:method name="buyGood"/>
</tx:attributes>
</tx:advice>

<!--配置aop,表示那些类需要应用事务-->
<aop:config>
<!--execution(* *..service..*.*(..)),表示所有返回值 ,所有包和子包的service中的子包的所有类和所有方法-->
<aop:pointcut id="servicePt" expression="execution(* *..service..*.*(..))"/>
<!--配置增强器,,关联事务的配置属性-->
<aop:advisor advice-ref="myAdvice" pointcut-ref="servicePt"/>
</aop:config>
</beans>

环境搭建完成

image-20220512143323492

展示数据实现分页

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
package com.zss.controller.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zss.controller.EmployeeController;
import com.zss.pojo.Employee;
import com.zss.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
* @author zss
*/
@Controller
public class EmployeeControllerImpl implements EmployeeController {


private EmployeeService employeeService;
@Autowired
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}

@Override
@RequestMapping("/show")
public ModelAndView showIndex(Integer pageNum) {
ModelAndView modelAndView=new ModelAndView();
PageHelper.startPage(pageNum,10);
List<Employee> employeeList=employeeService.getEmployees();
PageInfo<Employee> pageInfo=new PageInfo<>(employeeList);
modelAndView.addObject("employeeList",employeeList);
modelAndView.addObject("pageInfo",pageInfo);
modelAndView.setViewName("index");
return modelAndView;
}


}

在这里其实只需要传入一个域共享对象就好,但是这里thymeleaf不起作用,就传入了两个

使用JSON格式

其实这种方法适合电脑浏览器与服务器之间的结构,如果我们使用苹果或者安卓解析比较偏麻烦,那么这个适合就需要我们进行格式转换

浏览发送ajax请求进行员工分页数据的查询,服务器将查出的数据,以json字符串的形式返回浏览器,浏览器接收到json字符串,使用js对json进行解析

导入数据绑定的jackson包

方便我们进行自动转换

1
2
3
4
5
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.1</version>
</dependency>

更改源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Controller
public class EmployeeControllerImpl implements EmployeeController {


private EmployeeService employeeService;
@Autowired
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}

@Override
@ResponseBody
@RequestMapping("/show")
public PageInfo showIndex (@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum) {
PageHelper.startPage(pageNum,10);
List<Employee> employeeList=employeeService.getEmployees();
PageInfo<Employee> pageInfo=new PageInfo<>(employeeList,5);
return pageInfo;
}


}

image-20220512172020999

这是再次启动之后的数据情况,现在我们需要解析的是这些对象,但是这中情况发生在我们的查询操作中,但是如果是删除等等操作,我们又该如何返回浏览器信息那??

自定义数据状态

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
package com.zss.pojo;

import java.util.HashMap;
import java.util.Map;

public class Msg {
private int code;

private String msg;

private Map<String ,Object> extend=new HashMap<>();

public static Msg success(){
Msg result=new Msg();
result.setCode(100);
result.setMsg("操作成功");
return result;
}

public static Msg fail(){
Msg result=new Msg();
result.setCode(500);
result.setMsg("处理失败");
return result;
}

//方便我们进行链式操作
public Msg add(String key,Object value){
this.getExtend().put(key,value);
return this;
}

public int getCode() {
return code;
}

public void setCode(int code) {
this.code = code;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public Map<String, Object> getExtend() {
return extend;
}

public void setExtend(Map<String, Object> extend) {
this.extend = extend;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class EmployeeControllerImpl implements EmployeeController {


private EmployeeService employeeService;
@Autowired
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}

@Override
@ResponseBody
@RequestMapping("/show")
public Msg showIndex (@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum) {
PageHelper.startPage(pageNum,10);
List<Employee> employeeList=employeeService.getEmployees();
PageInfo<Employee> pageInfo=new PageInfo<>(employeeList,5);
return Msg.success().add("pageInfo",pageInfo);
}


}

image-20220512193059472

解析json数据

同时我们也是同vue.js代理thymeleaf的解析