SSM框架整合
1、基本环境搭建
环境要求:
- IDEA
- MySQL 5.7
- Tomcat 9
- Maven 3.6
创建数据库
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT ‘书id‘,
`bookName` VARCHAR(100) NOT NULL COMMENT ‘书名‘,
`bookCounts` INT(11) NOT NULL COMMENT ‘数量‘,
`detail` VARCHAR(200) NOT NULL COMMENT ‘描述‘,
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,‘Java‘,1,‘从入门到放弃‘),
(2,‘MySQL‘,10,‘从删库到跑路‘),
(3,‘Linux‘,5,‘从进门到进牢‘);
创建项目
新建一个空的Maven项目,创建后添加web支持。
导入项目相关的pom依赖
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!--Servlet JSP-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.9</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
</dependencies>
Maven静态资源过滤
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
建立基本结构和配置框架:在java目录下创建相应的包,以及在resources目录下创建基本的配置文件
-
com.xxx.pojo
-
com.xxx.dao
-
com.xxx.service
-
com.xxx.controller
-
mybatis-config.xml
<?xml version="1.0" encoding="UTF8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> </configuration>
-
applicationContext.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> </beans>
2、整合Mybatis
首先是Dao层对应的配置文件与接口的编写:
- 创建数据库配置文件:database.properties
jdbc.driver=com.mysql.jdbc.Driver
#如果使用的是MySQL8.0+,需要是URL的参数中增加一个时区的配置:&serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=123456
- 编写Mybatis的配置文件
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置数据源,交给Spring去做 -->
<settings>
<!--标准的日志工厂实现-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--是否开启驼峰命名自动映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.zyj.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.zyj.dao.BookMapper"/>
</mappers>
</configuration>
-
编写数据库对应的实体类:Books
使用lombok插件
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
-
编写Dao层的Mapper接口以及与接口对应的Mapper.xml文件
BookMapper接口
public interface BookMapper {
//新增一本书
int addBook(Books books);
//根据id删除一本书
int deleteBookById(@Param("bookID") int id);
//根据id修改一本书
int updateBook(Books books);
//根据id查询一本书
Books queryBookById(@Param("bookID") int id);
//查询表中所有书籍
List<Books> queryAllBook();
//根据书名查询一本书
Books queryBookByName(@Param("bookName") String bookName);
}
? BookMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zyj.dao.BookMapper">
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books (bookName, bookCounts, detail)
values (#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.books where bookID = #{bookID}
</delete>
<update id="updateBook" parameterType="Books">
update ssmbuild.books
set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID=#{bookID};
</update>
<select id="queryBookById" resultType="Books">
select * from ssmbuild.books where bookID=#{bookID}
</select>
<select id="queryAllBook" resultType="Books">
select * from ssmbuild.books
</select>
<select id="queryBookByName" resultType="Books">
select * from ssmbuild.books where bookName = #{bookName}
</select>
</mapper>
其次是业务层接口与实现类的编写:
-
service接口
public interface BookService { int addBook(Books books); int deleteBookById(int id); int updateBook(Books books); Books queryBookById(int id); List<Books> queryAllBook(); Books queryBookByName(String bookName); }
-
service接口实现类
public class BookServiceImpl implements BookService{ private BookMapper bookMapper; public void setBookMapper(BookMapper bookMapper) { this.bookMapper = bookMapper; } @Override public int addBook(Books books) { return bookMapper.addBook(books); } @Override public int deleteBookById(int id) { return bookMapper.deleteBookById(id); } @Override public int updateBook(Books books) { return bookMapper.updateBook(books); } @Override public Books queryBookById(int id) { return bookMapper.queryBookById(id); } @Override public List<Books> queryAllBook() { return bookMapper.queryAllBook(); } @Override public Books queryBookByName(String bookName) { return bookMapper.queryBookByName(bookName); } }
至此,使用Mybatis框架后的Dao层的基本业务代码以及调用Dao层执行业务的service层已经编写完毕。
3、整合Spring
上一个步骤中,我们并没有在Mybatis配置文件中配置数据源,因为要使用Spring框架,所以配置数据源的工作交由Spring来处理,这也是Spring整合Mybatis的关键。
新建一个配置文件:spring-dao.xml,这个xml文件只做与Dao层相关的Spring配置。
我们将创建多个Spring的配置文件,每一层对应一个,这样使得每一个配置文件只做该层相关的配置,并在applicationContext.xml中import它们,这样会使每个配置文件分工明确,便于编写和维护。
编写spring-dao.xml分为以下几步:
- 关联上一个步骤中引入的数据库配置文件:database.properties
- 配置数据源,这里使用c3p0连接池
- 配置sqlSessionFactory并绑定mybatis-config.xml
- 配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--1.关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!--2.连接池
dbcp:半自动化操作,不能自动连接
c3p0:自动化操作(自动化的加载配置文件,并且可以自动设置到对象中)
druid
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!--c3p0连接池的私有属性-->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!--关闭连接后不自动commit-->
<property name="autoCommitOnClose" value="false"/>
<!--获取连接超时时间-->
<property name="checkoutTimeout" value="10000"/>
<!--当获取连接失败重试次数-->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定Mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--4.配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入SQLSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫码的dao包-->
<property name="basePackage" value="com.zyj.dao"/>
</bean>
</beans>
Spring整合service层
同样新建配置文件:spring-service.xml
编写步骤如下:
- 扫描service包下的类
- 将业务接口的实现类注入到Spring(也可以使用注解,这里使用配置来实现)
- 声明式事务配置
- 可以在后面额外添加aop的事务支持,但目前的整合项目用不上所以就不添加了,如要添加则需要导入AOP相关依赖
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--1.扫描service下的包-->
<context:component-scan base-package="com.zyj.service"/>
<!--2.将我们的所有业务类,注入到Spring,可以通过配置,或注解实现-->
<bean id="BookServiceImpl" class="com.zyj.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3.声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4.aop事务支持-->
</beans>
至此,Dao层与业务层就整合到了Spring中,接下来整合SpringMVC。
4、整合SpringMVC
整合SpringMVC需要配置web.xml,在开头已经写到需要在项目中添加web支持,这里再次强调一下,如果没有找到web文件夹的朋友需要在项目中添加web支持,IDEA操作方法如下:
右键Project,点击Add Framework Support
勾选Web Application,并确认Create web.xml是勾选状态,点击OK
配置SpringMVC的第一件事是在web.xml中配置DispatcherServlet与乱码过滤。
<?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">
<!--DispatcherServlet-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.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>
<!--乱码过滤-->
<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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Session超时配置-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
然后创建spring-mvc.xml并配置
- 配置注解驱动
- 配置静态资源过滤
- 扫描controller包
- 配置视图解析器
<?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
https://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">
<!--1.注解驱动-->
<mvc:annotation-driven/>
<!--2.静态资源过滤-->
<mvc:default-servlet-handler/>
<!--3.扫描包:controller-->
<context:component-scan base-package="com.zyj.controller"/>
<!--4.视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
配置完spring-mvc.xml后,spring相关的配置就结束了,我们需要将这几个spring的配置文件导入总的配置文件中,也就是applicationContext.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
这样配置的好处在于,每一层相关的Spring的配置都分开了,每一个配置文件有明确的分工,如果将所有配置全部写入applicationContext中会非常的混乱,可读性低且不便于维护。
注意点:在web.xml中配置DispatcherServlet时需要引入SpringMVC的配置文件,此时需要填写applicationContext.xml,如果填写spring-mvc.xml会导致DispatcherServlet找不到业务层的bean而报错!
至此,框架的整合已经结束,但是这样还看不到任何效果,需要编写控制器与页面。
5、实现查询功能
框架已经整合完毕,需要编写控制器与jsp页面才能看到效果,这里做一个简单的查询,将数据库中books表中的所有数据查出来并展示到jsp页面上。
-
编写BookController
@Controller @RequestMapping("/book") public class BookController { //controller层调service层 @Autowired @Qualifier("BookServiceImpl") private BookService bookService; //查询全部的书籍,并且返回到一个书籍展示页面 @RequestMapping("/allBook") public String list(Model model){ List<Books> booksList = bookService.queryAllBook(); model.addAttribute("list",booksList); return "allBook"; } }
-
编写首页 index.jsp
点击a连接,跳转到书籍展示页面。
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>首页</title> </head> <body> <h3> <a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a> </h3> </body> </html>
-
编写书籍列表页面 allbook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>书籍展示</title> <head> <title>书籍列表</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 引入 Bootstrap --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="row clearfix"> <div class="col-md-12 column"> <div class="page-header"> <h1> <small>书籍列表 —— 显示所有书籍</small> </h1> </div> </div> </div> <div class="row clearfix"> <div class="col-md-12 column"> <table class="table table-hover table-striped"> <thead> <tr> <th>书籍编号</th> <th>书籍名字</th> <th>书籍数量</th> <th>书籍详情</th> </tr> </thead> <tbody> <c:forEach var="book" items="${list}"> <tr> <td>${book.bookID}</td> <td>${book.bookName}</td> <td>${book.bookCounts}</td> <td>${book.detail}</td> </tr> </c:forEach> </tbody> </table> </div> </div> </div> </body> </html>
-
页面编写完成之后,就可以配置Tomcat了
-
配置完Tomcat,启动Tomcat服务器,访问书籍展示页面,结果如下: