SSM框架整合
一.环境
1.1 SSM版本
- Mybatis 3.5.6
- Mybatis-spring 2.0.6
- Spring-webmvc 5.2.4
1.2MyBatis-Spring 适用的版本
1.2 相关依赖及静态资源导出(Maven)
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</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.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!--事务织入包-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
<!--静态资源导出-->
<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>
二.项目结构
###2.1结构目录
2.2pojo(实体类)
package com.zhang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
###2.2mapper(DAO)
2.2.1 BookMapper (interface)
package com.zhang.mapper;
import com.zhang.pojo.Book;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
int addBook(Book book);
int deleteBookById(@Param("bookID") int id);
int updateBook(Book book);
Book selectBookById(@Param("bookID") int id);
List<Book> selectAllBook();
List<Book> selectByName(String bookName);
}
2.2.2 BookMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhang.mapper.BookMapper">
<insert id="addBook" parameterType="Book">
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="Book">
update ssmbuild.books
set bookName = #{bookName},
bookCounts=#{bookCounts},
detail=#{detail}
where bookID = #{bookID}
</update>
<select id="selectBookById" parameterType="_int" resultType="Book">
select *
from ssmbuild.books
where bookID = #{bookID}
</select>
<select id="selectAllBook" resultType="Book">
select *
from ssmbuild.books
</select>
<select id="selectByName" parameterType="string" resultType="Book">
SELECT * FROM ssmbuild.books WHERE books.bookName LIKE CONCAT('%' #{bookName} '%');
</select>
</mapper>
2.3 service
2.3.1BookService(interface)
package com.zhang.service;
import com.zhang.pojo.Book;
import java.util.List;
public interface BookService {
int addBook(Book book);
int deleteBookById(int id);
int updateBook(Book book);
Book selectBookById(int id);
List<Book> selectAllBook();
List<Book> selectByName(String bookName);
}
2.3.2 BookServiceImpl
package com.zhang.service;
import com.zhang.mapper.BookMapper;
import com.zhang.pojo.Book;
import java.util.List;
public class BookServiceImpl implements BookService {
//service掉dao层 : 组合dao
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Book book) {
return bookMapper.addBook(book);
}
@Override
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
@Override
public int updateBook(Book book) {
return bookMapper.updateBook(book);
}
@Override
public Book selectBookById(int id) {
return bookMapper.selectBookById(id);
}
@Override
public List<Book> selectAllBook() {
return bookMapper.selectAllBook();
}
@Override
public List<Book> selectByName(String bookName) {
return bookMapper.selectByName(bookName);
}
}
2.4controller
package com.zhang.controller;
import com.zhang.pojo.Book;
import com.zhang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
//controller 掉service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询全部书籍
@RequestMapping("/allBook")
public String toSelectBook(Model model) {
List<Book> books = bookService.selectAllBook();
model.addAttribute("books", books);
return "allBook";
}
//添加书籍的页面
@RequestMapping("/addBook")
public String toAddBook() {
return "addBook";
}
@RequestMapping("/addMethod")
//添加书籍的请求处理
public String addBook(Book book) {
bookService.addBook(book); //执行添操作
return "redirect:/book/allBook"; //重定向到展示书籍页面(该页面走一次就查询一次全部书籍并展示)
}
//修改书籍页面
@RequestMapping("/updateBook/{bookId}")
public String toUpdateBook(@PathVariable("bookId") int id, Model model) {
Book book = bookService.selectBookById(id);
model.addAttribute("book", book);
return "updateBook";
}
//修改书籍的请求处理
@RequestMapping("/updateMethod")
public String updateBook(Book book) {
bookService.updateBook(book);
return "redirect:/book/allBook";
}
//删除书籍页面请求处理
@RequestMapping("/deleteMethod/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
//根据书名搜索
@RequestMapping("/search")
public String searchBook(String bookName, Model model) {
List<Book> books = bookService.selectByName(bookName);
if (books.size() == 0) {
model.addAttribute("err","未找到相关书籍");
}
model.addAttribute("books", books);
return "allBook";
}
}
三.Spring配置文件
3.1 Spring整合Mybatis
3.1.1mybatis-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>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.zhang.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.zhang.mapper.BookMapper"/>
</mappers>
</configuration>
3.1.2 database.properties(数据库配置)
driver=org.gjt.mm.mysql.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode&characterEncoding=UTF-8
user=root
password=***********
3.1.3 spring-mapper.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">
<!-- 关联数据库配置文件 -->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 连接池 这里使用第三方的
dbcp:半自动化操作,不能自动连接
c3p0:自动化操作(自动化的加载配置文件,并且可以自动设置到对象中)
druid:hikari
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${user}"/>
<property name="password" value="${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"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 配置dao接口扫描包,动态的实现dao(mapper)接口可以注入到Spring容器中 之前是通过 BookMapperImpl实现类去实现的-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 要扫描的dao包 -->
<property name="basePackage" value="com.zhang.mapper"/>
</bean>
</beans>
3.2 Spring将Service层进行整合
3.2.1 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
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/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">
<!-- 扫描service下的包 -->
<context:component-scan base-package="com.zhang.service"/>
<!-- 将我们的所有业务类注入到Spring,可以通过配置和注解实现 -->
<bean id="BookServiceImpl" class="com.zhang.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 声明式事务配置 -->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<!-- 注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- aop事务支持 结合AOP实现事务的织入-->
<!-- 配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些方法配置事务-->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务的切入 -->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.zhang.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
</beans>
3.3 配置SpringMVC
3.3.1 spring-mvc.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: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">
<!--注解驱动-->
<mvc:annotation-driven/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<!--扫描包-->
<context:component-scan base-package="com.zhang.controller"/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3.3.2 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">
<!-- 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>
<!-- 乱码过滤 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>10</session-timeout>
</session-config>
</web-app>
3.4 将所有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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-mapper.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
四.前端页面(WEB-INFO下的不可直接访问)
4.1 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>
<%-- 使用BootStrop美化 --%>
<link href="https://cdn.staticfile.org/twitter-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-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/addBook" role="button">新增书籍</a>
</div>
<div class="col-md-4 column">
<span style="color: brown;font-weight: bold">${err}</span>
</div>
<div class="col-md-4 column">
<form class="form-inline my-2 my-lg-0" action="${pageContext.request.contextPath}/book/search"
method="post">
<input class="form-control mr-sm-2" type="search" placeholder="书名" aria-label="Search" name="bookName">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">查询</button>
</form>
</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>
<th>操作</th>
</thead>
<tbody>
<c:forEach var="book" items="${books}" varStatus="idxStatus">
<tr>
<td><c:out value="${idxStatus.index+1}"/></td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/updateBook/${book.bookID}">修改</a> |
<a href="${pageContext.request.contextPath}/book/deleteMethod/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
4.2 addBook.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>
<%-- 使用BootStrop美化 --%>
<link href="https://cdn.staticfile.org/twitter-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-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/addBook" role="button">新增书籍</a>
</div>
<div class="col-md-4 column">
<span style="color: brown;font-weight: bold">${err}</span>
</div>
<div class="col-md-4 column">
<form class="form-inline my-2 my-lg-0" action="${pageContext.request.contextPath}/book/search"
method="post">
<input class="form-control mr-sm-2" type="search" placeholder="书名" aria-label="Search" name="bookName">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">查询</button>
</form>
</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>
<th>操作</th>
</thead>
<tbody>
<c:forEach var="book" items="${books}" varStatus="idxStatus">
<tr>
<td><c:out value="${idxStatus.index+1}"/></td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/updateBook/${book.bookID}">修改</a> |
<a href="${pageContext.request.contextPath}/book/deleteMethod/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
4.3 updateBook.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>
<%-- 使用BootStrop美化 --%>
<link href="https://cdn.staticfile.org/twitter-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-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/addBook" role="button">新增书籍</a>
</div>
<div class="col-md-4 column">
<span style="color: brown;font-weight: bold">${err}</span>
</div>
<div class="col-md-4 column">
<form class="form-inline my-2 my-lg-0" action="${pageContext.request.contextPath}/book/search"
method="post">
<input class="form-control mr-sm-2" type="search" placeholder="书名" aria-label="Search" name="bookName">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">查询</button>
</form>
</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>
<th>操作</th>
</thead>
<tbody>
<c:forEach var="book" items="${books}" varStatus="idxStatus">
<tr>
<td><c:out value="${idxStatus.index+1}"/></td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/updateBook/${book.bookID}">修改</a> |
<a href="${pageContext.request.contextPath}/book/deleteMethod/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
4.5 index.jsp
<%--
Created by IntelliJ IDEA.
User: admin
Date: 2021/9/14
Time: 14:11
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style>
h3 {
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 5px;
}
a {
text-decoration: none;
color: brown;
font-size: 18px;
}
</style>
</head>
<body>
<h3><a href="${pageContext.request.contextPath}/book/allBook">进入书籍展示页面</a></h3>
</body>
</html>
五.总结
-
页面发送请求给控制器(springMVC的范围),控制器调用业务层处理,业务层调用持久层(dao),持久层与数据库进行交互(mybatis的范围),然后将结果返回给业务层,业务层返回给控制层,控制层再调用视图展现数据(视图分发器,springMVC起的作用)。在整个过程中,spring作为一个容器,将整个过程装进去了。
-
Spring的优势
通过Spring的IOC特性,将对象之间的依赖关系交给了Spring控制,方便解耦,简化的开发。
通过Spring的AOP特性,对重复模块进行集中,实现事务,日志,权限的控制
-
SpringMVC的优势
SpringMVC是使用了MVC设计思想的轻量级web框架,对web层进行解耦使开发更简洁,与Spring无缝连接
-
Mybatis的优势
数据库的操作(sql)采用xml文件进行配置,SQL写在XML里,从程序代码中彻底分离,降低耦合度,便于统一管理和优化,可重用 ,与JDBC相比,减少了代码量就是简化了开发