声明:大部分内容来自b站博主《遇见狂神说》的视频!笔者也是基于视频所做的笔记,方便日后复习与查看!有不懂的地方可观看视频讲解!视频地址:https://www.bilibili.com/video/BV1aE41167Tu?p=17
Spring/SpringMVC/MyBatis框架整合
1、环境准备
为方便测试技术,我们以简单的《书籍信息管理系统》为例!首先我们要确保我们已经熟练掌握MySQL数据库,Spring,JavaWeb,SpringMVC及MyBatis知识,简单的前端知识。
1.1、数据库与数据表
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,'从进门到进牢');
1.2、基本环境搭建
1、使用maven创建一个新的web项目,并导入mybatis-spring,spring-jdbc,servlet,jsp,junit,spring-webmvc,mybatis,数据库驱动,数据库连接池,lombok的依赖并解决静态资源导出问题等。
pom.xml
<?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>com.howie</groupId>
<artifactId>ssm-build</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm-build 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>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--数据库驱动-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!--数据库连接池-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<!--servlet-->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jsp-->
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<!--mybatis与mybatis-spring-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<!--spring-mvc-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--spring-jdbc-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--lombok-->
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>ssm-build</finalName>
<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>
</project>
2、编写项目基本结构
基本结构已搭建完毕后面就是编写一些配置文件与静态资源!
1.3、编写MyBatis相关的资源
1、数据库配置文件 database.properties
# 据库连接需要的4个基本信息
prop.user=root
prop.password=101323
prop.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=FALSE&serverTimezone=UTC&allowPublicKeyRetrieval=true&characterEncoding=utf8
prop.driverClass=com.mysql.cj.jdbc.Driver
2、编写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">
<!--Mybatis核心配置文件-->
<configuration>
<!--配置别名-->
<typeAliases>
<package name="com.howie.pojo"/>
</typeAliases>
<!--设置-->
</configuration>
3、编写数据库对应的实体类 com.kuang.howie.Books
这里使用lombok插件
Books.java
/**
* @description: books实体类
* @author: laizhenghua
* @date: 2020/11/21 15:57
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private Integer bookID;
private String bookName;
private Integer bookCounts;
private String detail;
}
4、编写Dao层的 Mapper接口
/**
* @description: BooksMapper接口
* @author: laizhenghua
* @date: 2020/11/21 16:09
*/
public interface BooksDao {
// 增加一本书
int addBook(Books book);
// 删除一本书
int deleteBookById(Integer bookID);
// 修改一本书的信息
int updateBook(Books book);
// 根据id查询一本书
Books queryBookById(Integer bookID);
// 查询所有书籍
List<Books> queryAllBook();
}
5、编写接口对应的 xml映射 文件。需要导入MyBatis的包
BooksDao.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映射文件-->
<mapper namespace="com.howie.dao.BooksDao">
<!--增加一本书-->
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books(bookName, bookCounts, detail) value
(#{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>
<!--根据id查询一本书-->
<select id="queryBookById" parameterType="int" resultType="Books">
select * from ssmbuild.books where bookID = #{bookID}
</select>
<!--查询所有书籍-->
<select id="queryAllBook" resultType="Books">
select * from ssmbuild.books
</select>
</mapper>
6、编写Service层的接口和实现类
BooksService接口
/**
* @description: BooksService接口
* @author: laizhenghua
* @date: 2020/11/21 16:42
*/
public interface BooksService {
// 增加一本书
int addBook(Books book);
// 删除一本书
int deleteBookById(@Param("bookID") Integer bookID);
// 修改一本书的信息
int updateBook(Books book);
// 根据id查询一本书
Books queryBookById(@Param("bookID") Integer bookID);
// 查询所有书籍
List<Books> queryAllBook();
}
BooksService接口实现类
/**
* @description: 接口实现类,业务层还需要调用dao层
* @author: laizhenghua
* @date: 2020/11/21 16:43
*/
public class BooksServiceImpl implements BooksService {
private BooksDao booksDao;
// 调用dao层的操作,设置一个set接口,方便Spring管理
public void setBooksDao(BooksDao booksDao) {
this.booksDao = booksDao;
}
@Override
public int addBook(Books book) {
return booksDao.addBook(book);
}
@Override
public int deleteBookById(Integer bookID) {
return booksDao.deleteBookById(bookID);
}
@Override
public int updateBook(Books book) {
return booksDao.updateBook(book);
}
@Override
public Books queryBookById(Integer bookID) {
return booksDao.queryBookById(bookID);
}
@Override
public List<Books> queryAllBook() {
return booksDao.queryAllBook();
}
}
OK,到此,底层需求操作编写完毕!
1.4、编写Spring整合MyBatis的配置文件
1、配置Spring整合MyBatis,我们这里数据源使用阿里的druid连接池;
2、我们去编写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
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置整合MyBatis-->
<!--1、加载数据库配置信息(引入外部属性文件)-->
<context:property-placeholder location="classpath:db.properties"/>
<!--2、配置数据库连接池,这里使用druid-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${prop.driverClassName}"/>
<property name="url" value="${prop.url}"/>
<property name="username" value="${prop.username}"/>
<property name="password" value="${prop.password}"/>
<property name="initialSize" value="10"/>
<property name="maxActive" value="10"/>
</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"/>
<!--配置Mapper映射文件-->
<property name="mapperLocations" value="classpath:com/howie/dao/*.xml"/>
</bean>
<!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
<!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.howie.dao"/>
</bean>
</beans>
3、Spring整合service层
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--1、开启注解扫描,扫描service下的包-->
<context:component-scan base-package="com.howie.service"/>
<!--2、将所有业务类,注入到spring,可以通过配置或注解实现-->
<bean id="booksServiceImpl" class="com.howie.service.impl.BooksServiceImpl">
<property name="booksDao" ref="booksDao"/>
</bean>
<!--3、声明式事务的配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--aop织入事务-->
</beans>
1.5、编写Spring整合SpringMVC的相关配置文件
1、web.xml
<!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>
<!--注册Spring提供的过滤器,解决参数中文乱码问题-->
<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--注册前端控制器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><!--所有请求都会被springmvc拦截 -->
</servlet-mapping>
</web-app>
2、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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置SpringMVC -->
<!--1、开启SpringMVC注解驱动-->
<mvc:annotation-driven/>
<!--2、过滤静态资源,默认servlet配置-->
<mvc:default-servlet-handler/>
<!--3、开启注解扫描,扫描controller包下的注解-->
<context:component-scan base-package="com.howie.controller"/>
<!--4、视图解析器,配置jsp 显示ViewResolver视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3、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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://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>
到此ssm整合工作已全部完成!接下来我们就可以配合前端编写功能!
2、配合前端,业务功能的实现
2.1、查询书籍功能
1、编写控制层BooksController,并添加一个方法处理查询书籍请求!
/**
* @description: 控制层BooksController,需要调用service层
* @author: laizhenghua
* @date: 2020/11/21 20:11
*/
@Controller
@RequestMapping(path = "/book")
public class BooksController {
// 调用业务层service
@Autowired
@Qualifier(value = "booksServiceImpl")
private BooksService booksService;
/**
* @description: 查询全部的书籍,并且返回到书籍展示页面
* @author: laizhenghua
* @date: 2020/11/21 20:26
* @param: model
* @return: java.lang.String
*/
@RequestMapping(path = "/getAllBook")
public String list(Model model){
List<Books> booksList = booksService.queryAllBook();
model.addAttribute("books",booksList);
return "all_book";
}
}
2、编写首页 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
%>
<html>
<head>
<title>首页</title>
<style>
h2{
width: 500px;
height: 38px;
margin: 100px auto;
text-align: center;
background: aqua;
border-radius: 6px;
}
a{
text-decoration: none;
color: black;
text-align: center;
}
</style>
</head>
<body>
<h2>欢迎来到书籍信息管理系统</h2>
<a href="<%=path%>/book/getAllBook">书籍信息</a>
</body>
</html>
3、书籍列表页面 all_book.jsp
这里使用JSTL表达式需要引入表达式依赖和标签库
<!-- JSTL表达式的依赖 -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!-- standard标签库 -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
all_book.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: laizhenghua
Date: 2020/11/21
Time: 20:25
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>书籍信息页</title>
<!--引入BootStrap核心css文件-->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</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>
<th>操作</th>
</tr>
</thead>
<!--书籍从数据库中查询出来,从这个bookList中遍历出来:foreach-->
<%--${
requestScope.get("books")}--%>
<tbody>
<c:forEach var="book" items="${books}">
<tr>
<td>${
book.bookID}</td>
<td>${
book.bookName}</td>
<td>${
book.bookCounts}</td>
<td>${
book.detail}</td>
<td><input class="btn btn-small btn-primary" value="编辑"></td>
<td><input class="btn btn-small btn-danger" value="删除"></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
2.2、添加书籍功能
1、首先编写添加书籍页面 add_book.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>
<html>
<head>
<title>添加书籍</title>
<meta charset="UTF-8">
<!--引入BootStrap核心css文件-->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</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>
<form class="form-inline" action="<%=path%>/book/addBook" method="post">
<div class="form-group">
<label for="exampleInputName2">书籍名称</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="书籍名称" name="bookName" required>
</div>
<div class="form-group">
<label for="exampleInputEmail2">书籍数量</label>
<input type="text" class="form-control" id="exampleInputEmail2" placeholder="书籍数量" name="bookCounts" required>
</div>
<div class="form-group">
<label for="example2">书籍详情</label>
<input type="text" class="form-control" id="example2" placeholder="书籍详情" name="detail" required>
</div>
<button type="submit" class="btn btn-default">提交</button> |
<button type="reset" class="btn btn-default">重置</button>
</form>
</div>
</body>
</html>
2、控制层BooksControlle,新增一个方法用于处理添加书籍请求
/**
* @description: 添加书籍,并跳转到书籍信息列表
* @author: laizhenghua
* @date: 2020/11/22 12:02
* @param: books
* @return: java.lang.String
*/
@RequestMapping(path = "/addBook")
public String addBook(Books books){
// System.out.println(books.toString());
booksService.addBook(books);
return "redirect:/book/getAllBook";
}
3、测试效果即可
2.3、编辑书籍信息功能
1、控制层BooksControlle,新添两个方法分别跳转到修改书籍页面和处理修改书籍请求!
/**
* @description: 根据id查询书籍信息,并跳转到编辑书籍信息页面
* @author: laizhenghua
* @date: 2020/11/22 13:13
* @param: bookID
* @param: model
* @return: java.lang.String
*/
@RequestMapping(path = "/toUpdatePage/{bookID}",method = RequestMethod.GET)
public String toUpdateBookPage(@PathVariable Integer bookID,Model model){
Books book = booksService.queryBookById(bookID);
// System.out.println(book);
model.addAttribute("book",book);
return "update_book";
}
/**
* @description: 修改书籍信息,并重定向到书籍信息列表页
* @author: laizhenghua
* @date: 2020/11/22 13:21
* @param: books
* @return: java.lang.String
*/
@RequestMapping(path = "/updateBook")
public String updateBook(Books books){
// System.out.println(books.toString());
int count = booksService.updateBook(books);
// System.out.println(count);
return "redirect:/book/getAllBook";
}
2、编写修改书籍页面update_book.jsp
update_book.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%
String path = request.getContextPath();
%>
<html>
<head>
<title>修改书籍</title>
<meta charset="UTF-8">
<!--引入BootStrap核心css文件-->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</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>
<form class="form-inline" action="<%=path%>/book/updateBook" method="post">
<input type="hidden" name="bookID" value="${book.bookID}">
<div class="form-group">
<label for="exampleInputName2">书籍名称</label>
<input type="text" class="form-control" id="exampleInputName2" value="${book.bookName}" name="bookName" required>
</div>
<div class="form-group">
<label for="exampleInputEmail2">书籍数量</label>
<input type="text" class="form-control" id="exampleInputEmail2" value="${book.bookCounts}" name="bookCounts" required>
</div>
<div class="form-group">
<label for="example2">书籍详情</label>
<input type="text" class="form-control" id="example2" value="${book.detail}" name="detail" required>
</div>
<button type="submit" class="btn btn-default">提交</button> |
<button type="reset" class="btn btn-default">重置</button>
</form>
</div>
</body>
</html>
2.4、删除书籍功能
1、控制层里添加新方法,用于处理删除请问
/**
* @description: 删除书籍信息,并跳转到书籍信息列表
* @author: laizhenghua
* @date: 2020/11/22 14:39
* @param: bookID
* @return: java.lang.String
*/
@RequestMapping(path = "/deleteBook/{bookID}")
public String deleteBook(@PathVariable Integer bookID){
booksService.deleteBookById(bookID);
return "redirect:/book/getAllBook";
}
2、前端修改的删除按钮
<%--${requestScope.get("books")}--%>
<tbody>
<c:forEach var="book" items="${books}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a class="btn btn-primary" href="<%=path%>/book/toUpdatePage/${book.bookID}">编辑</a>
<a class="btn btn-danger" href="<%=path%>/book/deleteBook/${book.bookID}">删除</a><!--删除按钮-->
</td>
</tr>
</c:forEach>
</tbody>
2.5、搜索书籍功能
1、首先我们先在书籍信息列表页里,添加查询书籍的输入框和按钮
<div class="row">
<div class="col-md-4 column">
<button class="btn"><a href="<%=path%>/add_book.jsp">添加书籍</a></button>
<button class="btn"><a href="<%=path%>/book/getAllBook">显示所有书籍</a></button>
</div>
<div class="col-md-4 column form-inline">
<form action="<%=path%>/book/searchBook" method="post">
<!--搜索书籍功能-->
<input type="search" class="form-control" id="search" placeholder="输入查询书籍名称" name="queryBookName">
<input type="submit" class="btn" value="查询">
</form>
</div>
</div>
2、dao层添加一个抽象方法
// 根据名称模糊查询书籍
List<Books> searchBook(@Param("queryBookName") String queryBookName);
3、dao映射文件添加SQL语句
<!--模糊查询,注意这里当#{queryBookName}等于null时,会查询全部数据-->
<select id="searchBook" parameterType="String" resultType="Books">
select * from ssmbuild.books where bookName like '%' #{queryBookName} '%'
</select>
4、service接口层,添加搜索抽象方法
// 根据名称模糊查询书籍
List<Books> searchBook(@Param("queryBookName") String queryBookName);
5、service接口实现类
@Override
public List<Books> searchBook(String queryBookName) {
return booksDao.searchBook(queryBookName);
}
6、controller层里的BooksController类里也新添一个方法,用户处理搜索书籍请求。
/**
* @description: 根据书名,进行模糊查询,并返回书籍信息列表页
* @author: laizhenghua
* @date: 2020/11/22 16:08
* @param: queryBookName
* @param: model
* @return: java.lang.String
*/
@RequestMapping(path = "/searchBook")
public String searchBook(@RequestParam("queryBookName") String queryBookName,Model model){
List<Books> books = booksService.searchBook(queryBookName);
model.addAttribute("books",books);
return "all_book";
}
到此,我们ssm整合练习已全部完成,项目还有很多不合理和值得去优化的地方,我们就不过多去研究了,这里就当做练习。熟悉框架整合和项目开发流程,就可以了!代码可能也有很多看不懂的地方,为了学习方便,我会把所有代码发布到 gitee 里面。大家感兴趣的去看看哦!
3、完整代码Gitee地址
ssmbuild的gitee地址:https://gitee.com/laizhenghua/ssmbuild