java SSM利用Spring整合笔记
1. 导入依赖
<dependencies>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--spring-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
2. 文件架构
文件头汇总
mybatis配置文件
<?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>
</configuration>
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
3. 各文件夹解释
- controller层:控制层,用于进行业务处理,如获取数据,跳转页面等
- dao层:持久层,用于定义一些获取数据的接口,如获取全部书籍
- domian层:域模型层,用于封装实体
- service层:业务层,引用对应的DAO层数据库操作
项目运行的的流程:
- 用于提交请求到servlet或controller层
- controller层或servlet层根据具体要求调用service层
- service层引用对应的Dao层
- Dao层到数据库获取数据
- Dao层获取数据后返回service层再返回controller或servlet层
- servlet层或controller层转发到前端页面
4. 编写domain层和数据库配置文件
// Books.java
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
public Books(int bookID, String bookName, int bookCounts, String detail) {
this.bookID = bookID;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookCounts() {
return bookCounts;
}
public void setBookCounts(int bookCounts) {
this.bookCounts = bookCounts;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@Override
public String toString() {
return "Books{" + "bookID=" + bookID + ", bookName='" + bookName + '\'' + ", bookCounts=" + bookCounts + ", detail='" + detail + '\'' + '}';
}
}
# database.properties
spring.datasource.driver=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssmbuild?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
spring.datasource.username=root
spring.datasource.password=123456
# 创建数据库
CREATE DATABASE ssmbuild;
USE ssmbuild;
CREATE TABLE `books`(
`bookID` INT NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT 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,'从进门到进牢')
5. 整合Mybatis和Dao层
- Dao层一般需要两个文件
xxxDao(xxxxMapper).java,用于编写数据接口,对应到操作数据库
// BookMapper.java
public interface BookMapper {
/**
* 查询所有的书籍
* @return 返回所有的书籍信息
*/
List<Books> findAllBooks();
/**
* 根据ID查询书籍
* @param bookID
* @return 返回书籍信息
*/
Books findBookByID(int bookID);
/**
* 增加书籍
* @param book
* @return 返回是否成功
*/
int addBooks(Books book);
/**
* 删除书籍
* @param bookID
* @return 返回是否成功
*/
int deleteBooks(int bookID);
/**
* 修改书籍
* @param book
* @return 返回是否成功
*/
int updateBooks(Books book);
}
xxxDao(xxxMapper).xml,用于配置数据库的增删改查具体操作
<!--BookMapper.xml-->
<?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.zhanhang.dao.BookMapper">
<!--查询所有的书籍-->
<select id="findAllBooks" resultType="com.zhanhang.domain.Books">
select * from books;
</select>
<!--根据ID查询书籍-->
<select id="findBookByID" parameterType="int" resultType="com.zhanhang.domain.Books">
select * from books where bookID = #{bookID}
</select>
<!--增加书籍-->
<insert id="addBooks" parameterType="Books">
insert into books values (#{bookID},#{bookName},#{bookCounts},#{detail})
</insert>
<!--删除书籍-->
<delete id="deleteBooks" parameterType="int">
delete from books where bookID = #{bookID}
</delete>
<!--修改书籍-->
<update id="updateBooks" parameterType="Books">
update books set bookName = #{bookName}, bookCounts = #{bookCounts}, detail = #{detail} where bookID = {#bookID}
</update>
</mapper>
- mybatis配置文件
<!--mybatis-config.xml-->
<?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>
<typeAliases>
<package name="com.zhanhang.domain"/>
</typeAliases>
</configuration>
- spring整合Mybatis
<!--spring-dao.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
http://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. 关联数据库-->
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${spring.datasource.driver}" />
<property name="url" value="${spring.datasource.url}" />
<property name="username" value="${spring.datasource.username}" />
<property name="password" value="${spring.datasource.password}" />
</bean>
<!--3. 创建sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource" />
<!--绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="mapperLocations" value="classpath:com/zhanhang/dao/BookMapper.xml" />
</bean>
<!--4. 配置dao接口扫描包,动态实现Dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.zhanhang.dao"/>
</bean>
</beans>
6. 整合service层
-
文件编写:service层有两类文件
接口文件
// BookService.java
public interface BookService {
/**
* 查询所有的书籍
* @return 返回所有的书籍信息
*/
List<Books> findAllBooks();
/**
* 根据ID查询书籍
* @param bookID
* @return 返回书籍信息
*/
Books findBookByID(int bookID);
/**
* 增加书籍
* @param book
* @return 返回是否成功
*/
int addBooks(Books book);
/**
* 删除书籍
* @param bookID
* @return 返回是否成功
*/
int deleteBooks(int bookID);
/**
* 修改书籍
* @param book
* @return 返回是否成功
*/
int updateBooks(Books book);
}
接口实现类
// BookServiceImpl.java
public class BookServiceImpl implements BookService {
private BookMapper bookMapper;
/** 设置set接口方便spring调用 */
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public List<Books> findAllBooks() {
return bookMapper.findAllBooks();
}
public Books findBookByID(int bookID) {
return bookMapper.findBookByID(bookID);
}
public int addBooks(Books book) {
return bookMapper.addBooks(book);
}
public int deleteBooks(int bookID) {
return bookMapper.deleteBooks(bookID);
}
public int updateBooks(Books book) {
return bookMapper.updateBooks(book);
}
}
- 编写配置文件
<!--spring-service.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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--1. 扫描包-->
<context:component-scan base-package="com.zhanhang.service" />
<!--2. 注入容器-->
<bean id="BookServiceImpl" class="com.zhanhang.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper" />
</bean>
<!--3. 声明式事务-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean>
<!--4. aop事务支持-->
<!-- <tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!–配置事务织入–>
<aop:config>
<aop:pointcut id="aopPoint" expression="execution(* com.zhanhang.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="aopPoint"/>
</aop:config>-->
</beans>
7. 整合springMVC
<!--spring-mvc-->
<?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
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--1. 扫描包-->
<context:component-scan base-package="com.zhanhang.controller" />
<!--2. 静态资源过滤-->
<mvc:default-servlet-handler />
<!--3. 注解驱动-->
<mvc:annotation-driven />
<!--4. 视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"/>
</bean>
</beans>
8. 编写controller层
// BookController.java
@Controller
public class BookController {
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/list")
private String test(Model model){
List<Books> booksList = bookService.findAllBooks();
model.addAttribute("list",booksList);
return "list";
}
}
9. 配置web.xml以及编写jsp文件
- list.jsp
<%--list.jsp--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<html>
<head>
<title>书籍展示</title>
</head>
<style>
.book-table{
width: 80%;
margin: 50px auto;
}
</style>
<body>
<h2>书籍展示</h2>
<div class="container">
<div class="book-table">
<table class="table table-striped table-hover ">
<tr><th>ID</th><th>书籍名称</th><th>书籍数量</th><th>书籍描述</th></tr>
<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>
</body>
</html>
- web.xml
<!--web.xml-->
<?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">
<!--1. 注册DispatcherServlet-->
<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:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--2. 字符串乱码过滤器-->
<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>
<!--3. Session过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
10. 配置Tomcat,运行测试
<!--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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-dao.xml" />
<import resource="classpath:spring-mvc.xml" />
<import resource="classpath:spring-service.xml" />
</beans>
总结
spring整合mybatis的步骤
- 编写mybatis配置文件(mybatis-config.xml),当使用spring时,此文件非必要文件
- 整合(spring-dao.xml):
- 加载配置文件,关联数据库
- 创建sqlSessionFactory
- 扫描Dao层的包,动态注入到Spring中
spring整合service的步骤
- 扫描service的包
- 注入Spring容器
- 声明式事务
- aop事务支持
spring整合springMVC步骤
- 扫描包
- 静态资源过滤
- 注解驱动
- 配置视图解析器