1. 新建一个Maven项目
2. 设置项目默认构建编码
<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>
3. 导入依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<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>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
4. 设置Maven静态资源过滤
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
5. 创建books表并插入测试数据
CREATE TABLE IF NOT EXISTS `books`(
`bookID` INT NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT 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,'从进门到进牢');
6. 添加pojo、dao、service、controller、interceptor包

7. 添加Mybatis配置文件设置包别名和日志
<?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.wlp.pojo"/>
</typeAliases>
</configuration>
8. 添加Spring中applicationContext.mxl配置文件
9. 添加jdbc的properties文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?serverTimezone=UTC
jdbc.user=root
jdbc.password=8888
10. 编写pojo层(books实体)
package com.wlp.pojo;
public class Books {
private int bookId;
private String bookName;
private int bookCounts;
private String detail;
public Books() {
}
public Books(int bookId, String bookName, int bookCounts, String detail) {
this.bookId = bookId;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookCounts() {
return bookCounts;
}
public void setBookCounts(int bookCounts) {
this.bookCounts = bookCounts;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@Override
public String toString() {
return "Books{" +
"bookId=" + bookId +
", bookName='" + bookName + '\'' +
", bookCounts=" + bookCounts +
", detail='" + detail + '\'' +
'}';
}
}
11. 编写Dao层
1、编写BooksDaoMapper接口
package com.wlp.dao;
import com.wlp.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BooksDaoMapper {
int addBooks(Books books);
int deleteBooks(@Param("bookId") int bookId);
int updateBooks(Books books);
Books getQuery(@Param("bookId") int bookId);
List<Books> getQueryAll();
}
2、编写BooksDaoMapper配置文件
<?xml version="1.0" encoding="gbk" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wlp.dao.BooksDaoMapper">
<insert id="addBooks" parameterType="Books">
insert into ssmbuild.books(bookId,bookName,bookCounts,detail)values(#{bookId},#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBooks" parameterType="int">
delete from ssmbuild.books where bookId = #{bookId};
</delete>
<update id="updateBooks" parameterType="Books">
update ssmbuild.books set
bookName = #{bookName},
bookCounts = #{bookCounts},
detail = #{detail} where bookId = #{bookId};
</update>
<select id="getQuery" parameterType="int" resultType="Books">
select * from ssmbuild.books where bookId = #{bookId};
</select>
<select id="getQueryAll" resultType="Books">
select * from ssmbuild.books;
</select>
</mapper>
12. 编写Service层
1、编写BooksService接口
package com.wlp.service;
import com.wlp.pojo.Books;
import java.util.List;
public interface BooksService {
int addBooks(Books books);
int deleteBooks(int bookId);
int updateBooks(Books books);
Books getQuery(int bookId);
List<Books> getQueryAll();
}
2、编写BooksServiceImpl实现类
package com.wlp.service.impl;
import com.wlp.dao.BooksDaoMapper;
import com.wlp.pojo.Books;
import com.wlp.service.BooksService;
import java.util.List;
public class BooksServiceImpl implements BooksService {
private BooksDaoMapper booksDaoMapper;
public void setBooksDaoMapper(BooksDaoMapper booksDaoMapper) {
this.booksDaoMapper = booksDaoMapper;
}
public int addBooks(Books books) {
return booksDaoMapper.addBooks(books);
}
public int deleteBooks(int bookId) {
return booksDaoMapper.deleteBooks(bookId);
}
public int updateBooks(Books books) {
return booksDaoMapper.updateBooks(books);
}
public Books getQuery(int bookId) {
return booksDaoMapper.getQuery(bookId);
}
public List<Books> getQueryAll() {
return booksDaoMapper.getQueryAll();
}
}
13. 编写controller层
package com.wlp.controller;
import com.wlp.pojo.Books;
import com.wlp.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 {
@Autowired
@Qualifier("BooksServiceImpl")
private BooksService booksService;
@RequestMapping("/allBook")
public String list(Model model){
List<Books> queryAll = booksService.getQueryAll();
model.addAttribute("list",queryAll);
return "books/allBook";
}
@RequestMapping("/queryBook")
public String query(){
return "redirect:book/queryBook";
}
@RequestMapping("/addBook")
public String addBook(){
return "books/insertBook";
}
@RequestMapping("/insertBook")
public String insert(Books books){
booksService.addBooks(books);
return "redirect:/book/allBook";
}
@RequestMapping("/deleteBook/{bookId}")
public String delete(@PathVariable("bookId") int id){
booksService.deleteBooks(id);
return "redirect:/book/allBook";
}
@RequestMapping("/updateBook/{bookId}")
public String update(Model model,@PathVariable("bookId") int id){
Books query = booksService.getQuery(id);
System.out.println("需要更新的数据为:" + query);
model.addAttribute("book",query);
return "books/updateBook";
}
@RequestMapping("/toUpdateBooks")
public String toUpdateBook(Books books){
booksService.updateBooks(books);
return "redirect:/book/allBook";
}
}
14.编写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">
<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>
<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>15</session-timeout>
</session-config>
</web-app>
15. 编写interceptor拦截器
package com.wlp.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("=======拦截前========");
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("=======拦截后========");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("========清理==========");
}
}
16. 编写Spring配置文件
1、编写Spring-Dao.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
<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.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:Mybatis.xml"/>
<property name="mapperLocations" value="classpath:com/wlp/dao/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.wlp.dao"/>
</bean>
</beans>
2、编写Spring-Service.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="BooksServiceImpl" class="com.wlp.service.impl.BooksServiceImpl">
<property name="booksDaoMapper" ref="booksDaoMapper"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression="execution(* com.wlp.service.*.*(..))" id="txPointCut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
3、编写Spring-controller.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<context:component-scan base-package="com.wlp.controller"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.wlp.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
4、编写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-controller.xml"/>
</beans>
17. 编写JSP页面
0、开始页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style type="text/css">
a{
text-decoration: none;
color:black;
font-size: 18px;
}
h3{
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 4px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook" >点击进入书籍列表页</a>
</h3>
</body>
</html>
1、显示所有书籍页面
<%@ 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">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/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">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/addBook">新增</a>
</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="Books" items="${list}">
<tr>
<td>${Books.bookId}</td>
<td>${Books.bookName}</td>
<td>${Books.bookCounts}</td>
<td>${Books.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/updateBook/${Books.bookId}">更改</a>
<a href="/book/deleteBook/${Books.bookId}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</body>
</html>
2、编写更新页面
<%@ 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">
<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}/role/toUpdate" method="post">
<input type="hidden" name="bookId" value="${book.bookId}"/>
书籍名称:<input type="text" name="bookName" value="${book.bookName}"/>
书籍数量:<input type="text" name="bookCounts" value="${book.bookCounts}"/>
书籍详情:<input type="text" name="detail" value="${book.detail}"/>
<input type="submit" value="提交"/>
</form>
</div>
</body>
</html>
3、编写插入页面
<%@ 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">
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/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 action="${pageContext.request.contextPath}/book/insertBook" method="post">
书籍名称:<input type="text" name="bookName"><br><br><br>
书籍数量:<input type="text" name="bookCounts"><br><br><br>
书籍详情:<input type="text" name="detail"><br><br><br>
<input type="submit" value="添加">
</form>
</div>
</body>
</html>
18.配置Tomcat猫,测试