目錄
SSM整合案例:圖書管理系統
Spring + SpringMVC + MyBatis+JSP+Servlet+簡單前端知識
環境要求:
- IDEA
- MySQL 5.7.19
- Tomcat 9
- Maven 3.6
1、搭建數據庫環境
創建一個存放書籍數據的數據庫表:
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books`(
`bookID` INT(10) PRIMARY KEY AUTO_INCREMENT COMMENT '書id',
`bookName` VARCHAR(100) NOT NULL COMMENT '書名',
`bookCounts` INT(11) NOT NULL COMMENT '數量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述'
);
INSERT INTO `books`(`bookID`, `bookName`, `bookCounts`, `detail`)VALUES
(1,'Java',1,'從入門到放棄'),
(2,'MySQL',10,'從刪庫到跑路'),
(3,'Linux',5,'從進門到進牢');
SELECT * FROM books;
數據庫連接 url:
jdbc:mysql:/主機:3306/數據庫名稱?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
注:如果使用的是MySQL8.0+,url連接時增加一個時區的配置:serverTimezone=Asia/Shanghai
2、基本環境搭建
2.1、新建一個Maven項目,起名為:ssmbuild,添加web的支持
2.2、導入pom的相關依賴
<!--導入依賴 junit 數據庫連接 數據庫連接池 c3p0 Spring MyBatis mybatis-spring servlet jsp jstl-->
<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>
<!-- 數據庫連接池 -->
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<!--MyBatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</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>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
</dependencies>
2.3、Maven靜態資源過濾設置
<!--靜態資源過濾問題-->
<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.4、建立基本結構和配置框架!
java包:
- com.rainszj.pojo
- com.rainszj.dao
- com.rainszj.service
- com.rainszj.controller
resources包:
-
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> </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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> </beans> -
database.properties
3、MyBatis層編寫
3.1、pojo包
- Books
package com.rainszj.pojo;
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;
}
3.2、dao包
- BookMapper
package com.rainszj.dao;
import com.rainszj.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
/**
* 增加一本書
*
* @param books
* @return
*/
int addBook(Books books);
/**
* 刪除一本書
*
* @param id
* @return
*/
int deleteBook(@Param("bookId") int id);
/**
* 修改一本書
*
* @param book
* @return
*/
int updateBook(Books book);
/**
* 根據 id 查詢一本書
*
* @param id
* @return
*/
Books queryBookById(@Param("bookId") int id);
/**
* 查詢所有的書
*
* @return
*/
List<Books> queryAllBook();
}
- 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.rainszj.dao.BookMapper">
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books (bookName, bookCounts, detail)
values (#{bookName}, #{bookCounts}, #{detail})
</insert>
<delete id="deleteBook" 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>
</mapper>
3.3、resources
- 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>
<!--配置數據源,交給Spring-->
<!--其別名-->
<typeAliases>
<package name="com.rainszj.pojo"/>
</typeAliases>
<!--注冊Mapper-->
<mappers>
<mapper class="com.rainszj.dao"/>
</mappers>
</configuration>
- database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=root
3.4、service包
- BookService
package com.rainszj.service;
import com.rainszj.pojo.Books;
import java.util.List;
public interface BookService {
/**
* 增加一本書
*
* @param books
* @return
*/
int addBook(Books books);
/**
* 刪除一本書
*
* @param id
* @return
*/
int deleteBook(int id);
/**
* 修改一本書
*
* @param book
* @return
*/
int updateBook(Books book);
/**
* 根據 id 查詢一本書
*
* @param id
* @return
*/
Books queryBookById(int id);
/**
* 查詢所有的書
*
* @return
*/
List<Books> queryAllBook();
}
- BookServiceImpl
package com.rainszj.service;
import com.rainszj.dao.BookMapper;
import com.rainszj.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
// service層調dao層,使用組合dao
private BookMapper bookMapper;
// 使用Spring管理,實現set注入
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBook(int id) {
return bookMapper.deleteBook(id);
}
public int updateBook(Books book) {
return bookMapper.updateBook(book);
}
public Books queryBookById(int id) {
return queryBookById(id);
}
public List<Books> queryAllBook() {
return queryAllBook();
}
}
4、Spring層編寫
4.1、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.連接池
dbcp:半自動化操作(不能自動加載文件)
c3p0:自動化操作(自動加載配置文件,並且自動設置到對象中)
druid,hikari
-->
<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>
<!--3.SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入數據庫連接池-->
<property name="dataSource" ref="dataSource"/>
<!--配置mybatis配置文件:mybatis-config.xml-->
<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.rainszj.dao"/>
</bean>
</beans>
4.2、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 https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.掃描service相關的bean -->
<context:component-scan base-package="com.rainszj.service"/>
<!--2.將我們所有的業務類,注入到Spring中,可以通過配置或者注解實現-->
<bean id="BookServiceImpl" class="com.rainszj.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>
5、Spring MVC層編寫
5.1、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">
<!--注冊DispatchServlet-->
<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>
<!--Spring MVC內置的過濾器-->
<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過期時間-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
5.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
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.rainszj.controller"/>
<!--4.視圖解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
底層代碼編寫完畢,下面只需要編寫 Controller 層和 視圖層。
6、查詢書籍功能
6.1、BookController 類編寫 , 方法一:查詢全部書籍
@Controller
@RequestMapping("/book")
public class BookController {
// Controller 層調 Service 層
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
/**
* 查詢所有書籍
* @param model
* @return
*/
@RequestMapping("/allBook")
public String list(Model model) {
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
}
6.2、編寫首頁 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首頁</title>
<style>
a {
text-decoration: none;
color: #000;
font-size: 18px;
}
h3 {
width: 180px;
height: 38px;
margin: 200px auto;
text-align: center;
line-height: 38px;
background-color: deepskyblue;
border-radius: 5px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook">點擊到書籍列表</a>
</h3>
</body>
</html>
6.3、添加書籍列表頁面 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>
<%--BootStrap 美化界面--%>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<style>
</style>
</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">
<thread>
<tr>
<th>書籍編號</th>
<th>書籍名稱</th>
<th>書籍數量</th>
<th>書籍詳情</th>
</tr>
</thread>
<tbody>
<c:forEach var="book" items="${requestScope.get('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>
7、添加書籍
7.1、BookController 類編寫 , 方法二:添加書籍
/**
* 跳轉到修改頁面,並根據 id回顯數據
*
* @param id Book id
* @param model 傳給前端的數據
* @return
*/
@RequestMapping("/toUpdate/{bookId}")
public String toUpdatePaper(@PathVariable("bookId") int id, Model model) {
Books book = bookService.queryBookById(id);
model.addAttribute("QBook", book);
System.out.println(book);
return "updateBook";
}
/**
* 處理修改請求
*
* @param book 前端傳遞的對象
* @return
*/
@RequestMapping("/updateBook")
public String updateBook(Books book) {
int res = bookService.updateBook(book);
System.out.println(res);
if (res > 0) {
System.out.println("updateBook=>執行成功" + book);
}
return "redirect:/book/allBook";
}
7.2、在allBook.jsp中添加新增連接
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a>
</div>
</div>
7.3、添加書籍頁面:addBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加書籍</title>
<%--BootStrap 美化界面--%>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<%--row clearfix 清除浮動--%>
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>添加書籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
<div class="form-group">
<label for="bookName">書籍名稱</label>
<input type="text" name="bookName" class="form-control" id="bookName" required>
</div>
<div class="form-group">
<label for="bookCounts">書籍數量</label>
<input type="text" name="bookCounts" class="form-control" id="bookCounts" required>
</div>
<div class="form-group">
<label for="detail">書籍描述</label>
<input type="text" name="detail" class="form-control" id="detail" required>
</div>
<input type="submit" class="form-control" value="添加">
</form>
</div>
</body>
</html>
8、修改和刪除書籍
8.1、BookController 類編寫 , 方法三:修改書籍和刪除書籍
/**
* 跳轉到修改頁面,並根據 id回顯數據
*
* @param id Book id
* @param model 傳給前端的數據
* @return
*/
@RequestMapping("/toUpdate/{bookId}")
public String toUpdatePaper(@PathVariable("bookId") int id, Model model) {
Books book = bookService.queryBookById(id);
model.addAttribute("QBook", book);
System.out.println(book);
return "updateBook";
}
/**
* 處理修改請求
*
* @param book 前端傳遞的對象
* @return
*/
@RequestMapping("/updateBook")
public String updateBook(Books book) {
int res = bookService.updateBook(book);
System.out.println(res);
if (res > 0) {
System.out.println("updateBook=>執行成功" + book);
}
return "redirect:/book/allBook";
}
/**
* 刪除一本書
* @param id
* @return
*/
@RequestMapping("/deleteBook/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
bookService.deleteBook(id);
return "redirect:/book/allBook";
}
8.2、在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>
<%--BootStrap 美化界面--%>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<%--row clearfix 清除浮動--%>
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>書籍列表 —————— 顯示所有書籍</small>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<%--
table-hover: 鼠標滑過時,變色
table-striped: 每一行顯示不同的顏色
--%>
<table class="table table-hover table-striped">
<thread>
<tr>
<th>書籍編號</th>
<th>書籍名稱</th>
<th>書籍數量</th>
<th>書籍詳情</th>
<th>操作</th>
</tr>
</thread>
<tbody>
<c:forEach var="book" items="${requestScope.get('list')}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<%--傳統方式--%>
<%--
<a href="${pageContext.request.contextPath}/book/toUpdate?id=${book.bookID}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook?id=${book.bookID}">刪除</a>
--%>
<%--RestFul風格--%>
<a href="${pageContext.request.contextPath}/book/toUpdate/${book.bookID}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">刪除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
8.3、添加修改書籍頁面 updateBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改書籍</title>
<%--BootStrap 美化界面--%>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<%--row clearfix 清除浮動--%>
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>修改書籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<%--提交隱藏域,用於提交要修改書的 id--%>
<input type="hidden" name="bookID" value="${QBook.bookID}">
<div class="form-group">
<label for="bookName">書籍名稱</label>
<input type="text" name="bookName" class="form-control" id="bookName" value="${QBook.bookName}">
</div>
<div class="form-group">
<label for="bookCounts">書籍數量</label>
<input type="text" name="bookCounts" class="form-control" id="bookCounts" value="${QBook.bookCounts}">
</div>
<div class="form-group">
<label for="detail">書籍描述</label>
<input type="text" name="detail" class="form-control" id="detail" value="${QBook.detail}">
</div>
<input type="submit" class="form-control" value="修改">
</form>
</div>
</body>
</html>
9、搜索功能
9.1、在allBook.jsp中添加查詢書籍功能
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增書籍</a>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">查詢所有書籍</a>
</div>
<div class="col-md-8 column">
<%--查詢書籍--%>
<form action="${pageContext.request.contextPath}/book/queryBook" method="post" class="form-inline" style="float: right;">
<span style="color: red;font-weight: bold;">${error}</span>
<input type="text" class="form-control" name="queryBookName" placeholder="請輸入要查詢的書籍名稱"
style="width: 300px;">
<input type="submit" class="btn btn-primary" value="查詢">
</form>
</div>
</div>
9.2、在BookController類中編寫處理查詢書名的請求
/**
* 根據書名查詢一本書
*
* @param queryBookName
* @param model
* @return
*/
@RequestMapping("/queryBook")
public String queryBook(String queryBookName, Model model) {
List<Books> list = bookService.queryBookByName(queryBookName);
// System.err.println(list);
if (list.isEmpty()) {
list = bookService.queryAllBook();
model.addAttribute("error", "未找到!");
}
model.addAttribute("list", list);
return "allBook";
}
9.3、編寫BookMapper接口
/**
* 根據書名查詢一本書
*
* @param bookName
* @return
*/
List<Books> queryBookByName(@Param("bookName") String bookName);
9.4、在BookMapper.xml編寫Sql
<select id="queryBookByName" resultType="Books">
select * from ssmbuild.books where bookName = #{bookName}
</select>
9.5、編寫BookServicer接口
/**
* 根據書名查詢一本書
*
* @param bookName
* @return
*/
List<Books> queryBookByName(String bookName);
9.6、編寫BookServicerImpl
public List<Books> queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
10、項目結構:

11、注意事項
在 web.xml 中使用總的Spring配置文件!Spring MVC的內置過濾器要設置它的 encoding 屬性!

CharacterEncodingFilter 源碼中的 encoding 屬性

注意靜態資源過濾問題!

在項目的發布環境中添加lib依賴!

確保Spring Spring MVC 的配置文件在一個上下文中,將他們關聯在一起!

MapperScannerConfigurer
Mybatis MapperScannerConfigurer 自動掃描 將Mapper接口生成代理注入到Spring

