Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

回顾SSM框架整合

1、环境

  • jdk 1.8.0_271
  • Maven 3.6.1
  • mySQL 8.0
  • Tomcat 9.0.27

2、创建数据库

首先创建一个测试用的数据库 books:

1
2
3
4
5
6
7
8
create table books
(
bid int not null primary key,
sname varchar(255) null,
bname varchar(255) null,
bauthor varchar(255) null,
bhome varchar(255) null
);

This is a picture without description

3、创建项目

现在创建一个普通的 Maven 项目,并引入所需要的依赖

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

<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<spring.version>5.2.3.RELEASE</spring.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
</dependencies>

4、设置资源过滤

在 pom.xm 中插入资源过滤的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>

<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>

5、添加 web 框架支持

给我们创建的普通项目添加上框架支持,在项目名上右键,即可添加框架支持。
This is a picture without description
This is a picture without description

5、创建 spring 配置文件

在刚刚项目的 resources 下面创建配置文件 db.properties ,其中写的是数据库的相关配置

1
2
3
4
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF8&userSSL=true&serverTimezone=GMT
jdbc.username=chenyicai
jdbc.password=cyc1234

以及创建 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
69
70
71
72
73
74
75
76
77
<?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">

<!-- 使用连接池,开源的连接池-->
<!-- 阿里:druid-->
<!-- c3p0-->
<!-- hiraki:springboot默认使用的连接池-->
<!-- 一个应用最大并发如果有500个,那么为了提高查询效率,预先创建500个连接,并且把500个连接放入连接池(容器)-->

<!-- 控制器类的创建交给SpringMVC,不能配置在bean容器中 -->
<context:component-scan base-package="com.chen"></context:component-scan>

<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>

<!-- 初始化连接池中的连接数,取值应在minPoolSize与maxPoolSize之间,默认为3 -->
<property name="initialPoolSize" value="15"></property>

<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。默认值: 0 -->
<property name="maxIdleTime" value="0"></property>

<!--连接池中保留的最大连接数。默认值: 15 -->
<property name="maxPoolSize" value="100"></property>

<!-- 连接池中保留的最小连接数,默认为:3 -->
<property name="minPoolSize" value="10"></property>

<!--c3p0全局的PreparedStatements缓存的大小。如果maxStatements与maxStatementsPerConnection均为0,则缓存不生效,只要有一个不为0,则语句的缓存就能生效。如果默认值:
0 -->
<property name="maxStatements" value="200"></property>

<!-- 当连接池连接耗尽时,客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限期等待。单位毫秒。默认:
0 -->
<property name="checkoutTimeout" value="3000" />

<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
<property name="acquireIncrement" value="2" />

<!--定义在从数据库获取新连接失败后重复尝试的次数。默认值: 30 ;小于等于0表示无限次 -->
<property name="acquireRetryAttempts" value="0" />

<!--重新尝试的时间间隔,默认为:1000毫秒 -->
<property name="acquireRetryDelay" value="5000" />

<!--关闭连接时,是否提交未提交的事务,默认为false,即关闭连接,回滚未提交的事务 -->
<property name="autoCommitOnClose" value="false"></property>

<!--c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试使用。默认值:
null -->
<property name="automaticTestTable" value="Test"></property>

<!--如果为false,则获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常,但是数据源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。默认:
false -->
<property name="breakAfterAcquireFailure" value="false"></property>

<!--每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
<property name="idleConnectionTestPeriod" value="0"></property>

<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。默认值: 0 -->
<property name="maxStatementsPerConnection" value="10"></property>
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.chen.entity"></property>

</bean>
</beans>

6、编写代码主体

现在来编写代码中 entity,controller,service,mapper 层的代码
entity:books

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Books implements Serializable {
private Integer bid;

private String sname;

private String bname;

private String bauthor;

private String bhome;

private static final long serialVersionUID = 1L;

}

mapper(此处演示的是传统的 DAO 的方式):booksDao:

1
2
3
4
5
6
7
8
9
10
11
12
13
public interface BooksDao {
int deleteByPrimaryKey(Integer bid);

int insert(Books record);

int insertSelective(Books record);

Books selectByPrimaryKey(Integer bid);

int updateByPrimaryKeySelective(Books record);

int updateByPrimaryKey(Books record);
}

booksDaoImpl:

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
@Repository
public class BooksDaoImpl implements BooksDao {

private SqlSessionFactory sqlSessionFactory;

public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}

@Override
public int deleteByPrimaryKey(Integer bid) {
SqlSession sqlSession=sqlSessionFactory.openSession();
int out=sqlSession.delete("deleteByPrimaryKey",bid);
return out;
}

@Override
public int insert(Books record) {
SqlSession sqlSession=sqlSessionFactory.openSession();
int out=sqlSession.insert("insert",record);
return out;
}

@Override
public Books selectByPrimaryKey(Integer bid) {
SqlSession sqlSession=sqlSessionFactory.openSession();
Books books=sqlSession.selectOne("selectByPrimaryKey",bid);
return books;
}

@Override
public int updateByPrimaryKey(Books record) {
SqlSession sqlSession=sqlSessionFactory.openSession();
int out = sqlSession.update("updateByPrimaryKey",record);
return out;
}
}

然后是 xml 文件,其中是执行的 sql:

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
<?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="user">
<select id="selectByPrimaryKey" parameterType="int" resultType="com.chen.entity.Books">
select
*
from books
where bid = #{bid,jdbcType=INTEGER}
</select>

<delete id="deleteByPrimaryKey" parameterType="int">
delete from books
where bid = #{bid,jdbcType=INTEGER}
</delete>

<insert id="insert" parameterType="com.chen.entity.Books" useGeneratedKeys="true">
insert into books (sname, bname, bauthor,
bhome)
values (#{sname,jdbcType=VARCHAR}, #{bname,jdbcType=VARCHAR}, #{bauthor,jdbcType=VARCHAR},
#{bhome,jdbcType=VARCHAR})
</insert>

<update id="updateByPrimaryKey" parameterType="com.chen.entity.Books">
update books
set sname = #{sname,jdbcType=VARCHAR},
bname = #{bname,jdbcType=VARCHAR},
bauthor = #{bauthor,jdbcType=VARCHAR},
bhome = #{bhome,jdbcType=VARCHAR}
where bid = #{bid,jdbcType=INTEGER}
</update>
</mapper>

service 层:BooksService

1
2
3
4
5
6
7
8
9
public interface BooksService {
int deleteByPrimaryKey(Integer bid);

int insert(Books record);

Books selectByPrimaryKey(Integer bid);

int updateByPrimaryKey(Books record);
}

impl:

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 class BooksServiceImpl implements BooksService {

@Autowired
private BooksDao booksDao;

@Override
public int deleteByPrimaryKey(Integer bid) {
return booksDao.deleteByPrimaryKey(bid);
}

@Override
public int insert(Books record) {
return booksDao.insert(record);
}

@Override
public Books selectByPrimaryKey(Integer bid) {
return booksDao.selectByPrimaryKey(bid);
}

@Override
public int updateByPrimaryKey(Books record) {
return booksDao.updateByPrimaryKey(record);
}
}

最后是 Controller 层:BooksController

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
@RestController
public class BooksController {

@Autowired
private BooksService booksService;

public void setBooksService(BooksService booksService) {
this.booksService = booksService;
}

@RequestMapping("/del")
int deleteByPrimaryKey(Integer bid){
return booksService.deleteByPrimaryKey(bid);
}

@RequestMapping("/ins")
int insert(Books record){
return booksService.insert(record);
}

@RequestMapping("/sel")
Books selectByPrimaryKey(Integer bid){
return booksService.selectByPrimaryKey(bid);
}

@RequestMapping("/up")
int updateByPrimaryKey(Books record){
return booksService.updateByPrimaryKey(record);
}
}

最后项目的结构如下:
This is a picture without description

7、现在需要在配置 xml 中编写扫描我们的 bean 的代码

加入以下代码:

1
2
3
4
5
6
7
8
9
<bean id="userDao" class="com.chen.mapper.impl.BooksDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.chen.entity"></property>
<property name="mapperLocations" value="classpath*:mapper/BooksMapper.xml"></property>
</bean>

如图:
This is a picture without description
This is a picture without description

8、web 配置

在 web.xml 中配置以下内容,用于配置dispatcherServlet中心控制器

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"?>
<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">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<!-- 监听器会自动读取applicationContext.xml中的bean的信息,完成bean的初始化-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- 前端控制器 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern><!-- 处理所有请求,当然也包含静态资源(js、css、img...) -->
</servlet-mapping>
</web-app>

在创建一个 dispatcher-servlet.xml,用于 MVC 的装配

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

<!-- 扫描控制器的包,以确定哪些类是控制器类(哪些类上使用了@Controller注解) -->
<context:component-scan base-package="cn.edu.guet.controller"></context:component-scan>

<!-- 表示:所有的静态资源使用默认的Servlet -->
<mvc:default-servlet-handler></mvc:default-servlet-handler>

<mvc:annotation-driven></mvc:annotation-driven>


<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property><!-- 告诉SpringMVC去哪个目录找文件 -->
<property name="suffix" value=".jsp"></property><!-- 文件的后缀 -->
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!--通过处理器适配器AnnotationMethodHandlerAdapter来开启支持@RequestMapping注解-->

</beans>

9、运行测试

此时我们用 Tomcat 构建项目。
出现以下结果:
This is a picture without description

如果出现这种情况,我们就需要将 maven 的包手动导入,才能成功启动项目。
步骤如下:

  1. 打开项目结构。
  2. 点击构件,然后点击WEB-INF目录,点击新建文件夹按钮,创建lib文件夹。
  3. 然后引入库。
  4. 将其全选,然后需要的jar包便全部导入到项目中。
    This is a picture without description

再运行,即可