1、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.qing</groupId>
<artifactId>ssm-build</artifactId>
<version>1.0-SNAPSHOT</version>
<!--依赖-->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<!-- 数据库连接池 -->
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<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>
<!--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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
</dependencies>
<!-- 静态资源导出问题-->
<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>
</project>
2、配置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.qing.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.qing.mapper.BookMapper"/>
</mappers>
</configuration>
3、配置database.properties数据源
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=qing
#如果mysql8出现时区问题则添加下面一行
#serverTimezone=Asia/Shanghai&
4、配置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 连接池 c3p0
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}"/>
</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"/>
</bean>
<!--4 配置dao接口扫描包 动态实现dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 要扫描的包-->
<property name="basePackage" value="com.qing.mapper"/>
</bean>
</beans>
5、配置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相关的bean -->
<context:component-scan base-package="com.qing.service" />
<!--2 BookServiceImpl注入到IOC容器中-->
<bean id="BookServiceImpl" class="com.qing.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="datasource" />
</bean>
</beans>
6、配置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 注解驱动 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<context:component-scan base-package="com.qing.controller"/>
<!--2 静态资源过滤 让Spring MVC不处理静态资源 .css .js .html等-->
<mvc:default-servlet-handler />
<!--3 支持mvc注解驱动-->
<mvc:annotation-driven />
<!--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>
7、整合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-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
8、配置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>
<!--关联一个applicationContext.xml配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--启动级别-1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--/ 匹配所有的请求;(不包括.jsp)-->
<!--/* 匹配所有的请求;(包括.jsp)-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--解决乱码-->
<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>
<!--设置session15分钟过期-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
9、注意事项
(1)打开项目结构,点击Modules,选择项目下的Spring,查看四个配置文件是否都在ApplicationContext下
(2)Spring的三个配置文件必须整合到一起,使用import标签存放到一个applicationContext.xml中
(3)web.xml中注册DispatcherServlet时必须关联applicationContext.xml配置文件,这样才能加载所有的bean,包括service层的
10、Java代码
9.1 实体类
User实体类:
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;
}
9.2 mapper(dao)层
BookMappe接口:
public interface BookMapper {
//增加一本书
int addBook(Books book);
//删除一本书
int deleteBook(@Param("bookId") int id);
//修改一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(@Param("bookId") int id);
//查询所有
List<Books> queryAllBook();
//通过名字查询书籍
Books queryBookByName(@Param("bookName") String bookName);
}
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.qing.mapper.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="queryBookByName" resultType="Books">
select * from ssmbuild.books where bookName=#{bookName};
</select>
<select id="queryAllBook" resultType="Books">
select * from ssmbuild.books
</select>
</mapper>
9.3 service层
BookService接口:
import com.qing.pojo.Books;
import java.util.List;
public interface BookService {
//增加一本书
int addBook(Books book);
//删除一本书
int deleteBook(int id);
//修改一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(int id);
//查询所有
List<Books> queryAllBook();
//通过名字查询书籍
Books queryBookByName(String bookName);
}
BookServiceImpl实现类:
import com.qing.mapper.BookMapper;
import com.qing.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public BookMapper getBookMapper() {
return bookMapper;
}
@Override
public int addBook(Books book) {
return bookMapper.addBook(book);
}
@Override
public int deleteBook(int id) {
return bookMapper.deleteBook(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() {
return bookMapper.queryAllBook();
}
@Override
public Books queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
}
9.4 controller层
BookController:
import com.qing.pojo.Books;
import com.qing.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.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
//查询全部书籍并返回页面
public String list(Model model) {
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
//跳转到增加书籍页面
@RequestMapping("/toAddBook")
public String toAddBook() {
return "AddBook";
}
//添加书籍请求
@RequestMapping("/addBook")
public String addBook(Books book) {
if (book != null) {
System.out.println("addBook->" + book.toString());
bookService.addBook(book);
}
return "redirect:/book/allBook";
}
//跳转到修改页面
@RequestMapping("/toUpdateBook")
public String toUpdateBook(int id, Model model) {
Books book = bookService.queryBookById(id);
model.addAttribute("book", book);
return "updateBook";
}
//修改书籍
@RequestMapping("/updateBook")
public String updateBook(Books book) {
System.out.println("updateBook->" + book);
bookService.updateBook(book);
return "redirect:/book/allBook";
}
//删除书籍
@RequestMapping("/delBook/{bookID}")
public String deleteBook(@PathVariable("bookID") int id) {
System.out.println("delBook:" + bookService.queryBookById(id).toString());
bookService.deleteBook(id);
return "redirect:/book/allBook";
}
//查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName, Model model) {
Books books = bookService.queryBookByName(queryBookName);
if (books != null) {
System.out.println("queryBookByName:" + books.toString());
List<Books> list = new ArrayList<>();
list.add(books);
model.addAttribute("list", list);
return "allBook";
} else {
System.out.println("结果为空!");
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
model.addAttribute("error","未查到!");
return "allBook";
}
}
}
11、前端代码
10.1 index.jsp系统主页
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style>
a{
text-decoration: none;
color: black;
}
h3{
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: darkgoldenrod;
border-radius: 5px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook">进入所有书籍页面</a>
</h3>
</body>
</html>
10.2 allBook书籍主页
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍展示</title>
<!-- 新 Bootstrap 核心 CSS 文件 -->
<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 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">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示所有书籍</a>
</div>
<div class="col-md-4 column col-md-offset">
<form action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: left">
<span style="color: red;font-weight: bold">${error}</span>
<input type="text" name="queryBookName" placeholder="请输入要查询的书籍名称" required>
<input type="submit" value="查询" class="btn btn-primary">
</form>
</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>
<tbody>
<c:forEach var="book" items="${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/toUpdateBook?id=${book.bookID}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/delBook/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
10.3 AddBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>增加书籍</title>
<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>
<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="bookCount">书籍数量</label>
<input type="text" name="bookCounts" class="form-control" id="bookCount" required>
</div>
<div class="form-group">
<label for="bookDesc">书籍描述</label>
<input type="text" name="detail" class="form-control" id="bookDesc">
</div>
<button type="submit" class="btn btn-default">添加</button>
</form>
</div>
</body>
</html>