1、项目简介
使用SSM框架开发一个简单的图书管理系统,主要功能为表单数据的增删改查。
前端使用:JSP+Bootstrap
后端使用:SpringMVC+Spring+Mybatis
开发环境:
IDEA 2021.1.2
MySQL 5.7.19
Tomcat 9.0.50
Maven 3.8.1
2、整合Mybatis层
2.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,'从进门到进牢');
2.2、创建Maven项目
- 添加Web支持
- 导入依赖
<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.2</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>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</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.2</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
- 处理Maven静态资源过滤问题
<!--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.3、编写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>
<!--日志-->
<settings>
<!--标准的日志工厂STDOUT_LOGGING-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--别名映射-->
<typeAliases>
<package name="com.liuxiang.pojo"/>
</typeAliases>
<mappers>
<mapper resource="com/liuxiang/dao/BooksMapper.xml"/>
</mappers>
</configuration>
- 编写 database.properties
jdbc.driver=com.mysql.jdbc.Driver
# 使用Mybatis8.0+ 必须要设置时区serverTimezone=UTC
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
- 编写 pojo实体类
package com.liuxiang.pojo;
/**
* 数据库实体类
* @Author liuxiang
*/
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接口-BooksMapper
package com.liuxiang.dao;
/**
* dao层 Mapper接口
* @author liuxiang
*/
import com.liuxiang.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BooksMapper {
//增加一个Book
int addBook(Books book);
//根据id删除一个Book
int deleteBookById(@Param("bookId") int id);
//更新Book
int updateBook(Books books);
//根据id查询,返回一个Book
Books queryBookById(@Param("bookId") int id);
//如果不传参 则查询全部Book,返回list集合 如果传参 则查询具体内容
List<Books> queryAllBook(String bookName);
}
- 编写 BooksMapper.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">
<!--namespace 命名空间 指向 定义一个Dao接口-->
<mapper namespace="com.liuxiang.dao.BooksMapper">
<!--增加一个Book-->
<insert id="addBook" parameterType="books">
insert into books (bookName,bookCounts,detail)
values (#{bookName},#{bookCounts},#{detail})
</insert>
<!--根据id删除一个Book-->
<delete id="deleteBookById" parameterType="int">
delete from books where bookID=#{bookId}
</delete>
<!--更新一个book-->
<update id="updateBook" parameterType="books">
update books set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
</update>
<!--根据id查询,返回一个Book-->
<select id="queryBookById" parameterType="int" resultType="com.liuxiang.pojo.Books">
select * from books where bookID=#{bookId}
</select>
<!--传参则模糊查询 不传参则查全量数据-->
<select id="queryAllBook" parameterType="string" resultType="books">
select * from books
<where>
<if test="bookName != null">
bookName like concat('%',#{bookName},'%')
</if>
</where>
</select>
</mapper>
3、整合Spring层
3.1、Spring整合Mybatis
- 编写 mybatis-spring.xml(也可以叫spring-dao.xml 或者 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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!--数据库连接池 C3P0连接池-->
<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>
<!--获取SQLSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--SqlSessionTemplate 只能使用构造器注入 因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!--配置dao层接口扫描 动态实现Dao层接口注入容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入SQLSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的dao包-->
<property name="basePackage" value="com.liuxiang.dao"/>
</bean>
</beans>
3.2、编写Spring层文件
- 编写service层Service接口-BooksService
package com.liuxiang.service;
import com.liuxiang.pojo.Books;
import java.util.List;
public interface BooksService {
//增加一个Book
int addBook(Books book);
//根据id删除一个Book
int deleteBookById(int id);
//更新Book
int updateBook(Books books);
//根据id查询,返回一个Book
Books queryBookById(int id);
//如果不传参 则查询全部Book,返回list集合 如果传参 则查询具体内容
List<Books> queryAllBook(String bookName);
}
- 编写接口实现类 BooksServiceImpl
package com.liuxiang.service;
import com.liuxiang.dao.BooksMapper;
import com.liuxiang.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
public class BooksServiceImpl implements BooksService {
//调用dao层的操作,设置一个set接口,方便Spring管理
private BooksMapper bookMapper;
public void setBookMapper(BooksMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Books book) {
return bookMapper.addBook(book);
}
@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(String bookName) {
List<Books> books = bookMapper.queryAllBook(bookName);
if (books.size()==0){ //判断是否查询到值 如果没查询到 则查全量
books= bookMapper.queryAllBook(null);
}
return books;
}
}
- 编写 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">
<!--配置要扫描的service包-->
<context:component-scan base-package="com.liuxiang.service"/>
<!--配置注解支持-->
<context:annotation-config/>
<!--将我们所有的业务类,注入Spring,可以通过配置,也可以通过注解-->
<bean id="BookServiceImpl" class="com.liuxiang.service.BooksServiceImpl">
<property name="bookMapper" ref="booksMapper"/>
</bean>
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
- 编写总配置文件 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">
<!--spring配置文件-->
<import resource="mybatis-spring.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
4、整合SpringMVC层
4.1、编写SpringMVC层文件
- 编写 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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--注解驱动-->
<mvc:annotation-driven/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<!--扫描包-->
<context:component-scan base-package="com.liuxiang.controller"/>
<!--视图解析器:DispatcherServlet给他的ModelAndView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- 编写 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>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>
<!--encodingFilter 乱码过滤器-->
<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、编写业务代码
5.1、Controller代码编写
- 编写 BooksController
package com.liuxiang.controller;
/**
* Controller层
* @Author liuxiang
*/
import com.liuxiang.pojo.Books;
import com.liuxiang.service.BooksService;
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 BooksController {
//controller层调service层
@Autowired
private BooksService booksService;
/**
* 查询全部书籍
* @param model
* @return 返回书籍展示页面
*/
@RequestMapping("/allBook")
public String list(Model model){
List<Books> books = booksService.queryAllBook(null);
model.addAttribute("list",books);
return "allBook";
}
/**
* 查询指定名字的书籍
* @param queryBookName 要查询的书籍
* @param model 封装查询到的数据
* @return 返回页面 注意:此处不能使用重定向
*/
@RequestMapping("/queryBookName")
public String listall(String queryBookName,Model model){
String trim = queryBookName.trim();
List<Books> books = booksService.queryAllBook(trim);
model.addAttribute("list",books);
return "allBook";
}
/**
* 新增页面
* @return 跳转到新增书籍页面
*/
@RequestMapping("/toAddBook")
public String toaddBook(Model model){
model.addAttribute("msg","成功跳转页面");
return "addBook";
}
/**
* 新增书籍数据
* @param books 添加表单值
* @return 重定向到查询页
*/
@RequestMapping("/addBook")
public String addBook(Books books){
booksService.addBook(books);
return "redirect:/book/allBook";
}
/**
* 基于id查询对应数据 返回修改页面
* @param id 修改数据的id
* @param modle 封装书籍id对应的数据
* @return 返回一个修改页面
*/
@RequestMapping("/toUpdateBook")
public String updateBook(int id,Model modle){
Books books = booksService.queryBookById(id);
modle.addAttribute("Qbooks",books);
return "updateBook";
}
/**
* 修改表单数据
* @param books 修改数据
* @return 重定向到查询页
*/
@RequestMapping("/updateBook")
public String updateBook(Books books){
int i = booksService.updateBook(books);
return "redirect:/book/allBook";
}
/**
* 删除书籍
* @param bookID 需要删除的书籍id
* @return 重定向到查询页
*/
@RequestMapping("/del/{bookID}")
public String delBook(@PathVariable int bookID){
booksService.deleteBookById(bookID);
return "redirect:/book/allBook";
}
}
5.2、前端页面编写
- index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style>
h3 a{
color: darkcyan;
text-decoration: none;
font-family: fantasy;
font-size: 20px;
text-decoration: none;
}
h3{
width: 300px;
height: 300px;
margin: 0 auto;
text-align: center;
line-height: 300px;
background: bisque;
border-radius: 10px;
}
a:hover{
color: steelblue;
font-size: 30px;
}
</style>
</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>
<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">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a>
</div>
<div class="col-md-4 column"></div>
<div class="col-md-4 column">
<%--查询书籍--%>
<form class="form-inline" action="${pageContext.request.contextPath}/book/queryBookName" method="post" style="float: right">
<input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询的书籍">
<input type="submit" value="查询" class="btn btn-primary">
</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>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.getBookID()}</td>
<td>${book.getBookName()}</td>
<td>${book.getBookCounts()}</td>
<td>${book.getDetail()}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a> |
<a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
- 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>
<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>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
<div class="form-group">
<lable>书籍名称:</lable>
<input type="text" name="bookName" class="form-control" required>
</div>
<div class="form-group">
<lable>书籍数量:</lable>
<input type="text" name="bookCounts" class="form-control" required>
</div>
<div class="form-group">
<lable>书籍详情:</lable>
<input type="text" name="detail" class="form-control" required>
</div>
<div class="form-group">
<input type="submit" value="添加">
</div>
</form>
</div>
</body>
</html>
- 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>
<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>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<div class="form-group">
<lable>书籍id:</lable>
<input type="text" name="bookID" class="form-control" value="${Qbooks.bookID}" readonly>
</div>
<div class="form-group">
<lable>书籍名称:</lable>
<input type="text" name="bookName" class="form-control" value="${Qbooks.bookName}" required>
</div>
<div class="form-group">
<lable>书籍数量:</lable>
<input type="text" name="bookCounts" class="form-control" value="${Qbooks.bookCounts}" required>
</div>
<div class="form-group">
<lable>书籍详情:</lable>
<input type="text" name="detail" class="form-control" value="${Qbooks.detail}" required>
</div>
<div class="form-group">
<input type="submit" value="修改">
</div>
</form>
</div>
</body>
</html>
6、项目发布
- 配置 Tomcat
- 添加项目依赖到项目发布
- 项目展示