1、导入依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.8</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
2、搭建环境
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>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>
<!-- 解决前端传输数据到后端的中文乱码问题-->
<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>
</web-app>
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
//连接其余配置文件
<import resource="classpath:spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
mybatis.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做
<mappers>
<mapper class="dao.BookMapper"></mapper>
</mappers>
</configuration>
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
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--关联数据库配置文件-->
<!-- <context:property-placeholder location="db.properties"/>-->
<!--连接池-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode-true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定mybatis.xml配置文件-->
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>
<!--配置dao接口扫描包,动态的实现dao接口可以注入到spring容器之中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的dao包-->
<property name="basePackage" value="dao"/>
</bean>
===================
//对比之前写法
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="UserMapper" class="mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
</beans>
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
https://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="service"/>
<!--将所有业务类注入到spring容器中,交给spring管理,可以通过配置或注解实现-->
<bean class="service.BookServiceImpl" name="BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
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"
>
<context:component-scan base-package="controller"/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<!--注册驱动-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
基本配置,框架搭建完成后可开始写代码
由dao层->service->controller->视图 jsp
Book类
package pojo;
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
public Books(int bookID, String bookName, int bookCounts, String detail) {
this.bookID = bookID;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
@Override
public String toString() {
return "Books{" +
"bookID=" + bookID +
", bookName='" + bookName + '\'' +
", bookCounts=" + bookCounts +
", 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;
}
}
sql文件
/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 8.0.24 : Database - ssmbuild
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`ssmbuild` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `ssmbuild`;
/*Table structure for table `books` */
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` int NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` varchar(100) NOT NULL,
`bookCounts` int NOT NULL,
`detail` varchar(200) NOT NULL,
PRIMARY KEY (`bookID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*Data for the table `books` */
insert into `books`(`bookID`,`bookName`,`bookCounts`,`detail`) values (1,'java123',12,'从入门到放弃'),(2,'mysql',10,'从删库到跑路'),(3,'linux',5,'从进门到进牢');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
Dao
BookMapper:
package dao;
import pojo.Books;
import java.util.List;
public interface BookMapper {
//增加一本书
int addBook(Books book);
//删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books book);
//查询一本书
Books queryBookById(int id);
//查询全部的书
List<Books> queryAllBook();
//名字查询
Books queryBookByName(String bookName);
}
BookMapper.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 namespace="dao.BookMapper">
<insert id="addBook" parameterType="pojo.Books">
insert into ssmbuild.books(bookID,bookName, bookCounts, detail)
VALUES (#{bookID},#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.books
where bookID=#{bookID}
</delete>
<update id="updateBook" parameterType="pojo.Books">
update ssmbuild.books set bookName=#{bookName}
,bookCounts=#{bookCounts},detail=#{detail}
where bookID=#{bookID};
</update>
<select id="queryBookById" resultType="pojo.Books">
select *from ssmbuild.books where bookID=#{bookID}
</select>
<select id="queryAllBook" resultType="pojo.Books">
select *from ssmbuild.books;
</select>
<select id="queryBookByName" resultType="pojo.Books">
select *from ssmbuild.books where bookName=#{bookName};
</select>
</mapper>
service
调用dao层实现业务逻辑
BookService:
package service;
import pojo.Books;
import java.util.List;
public interface BookService {
//增加一本书
int addBook(Books book);
//删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books book);
//查询一本书
Books queryBookById(int id);
//查询全部的书
List<Books> queryAllBook();
//名字查询
Books queryBookByName(String bookName);
}
BookServiceImpl:
package service;
import dao.BookMapper;
import pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books book) {
return bookMapper.addBook(book);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books book) {
return bookMapper.updateBook(book);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
public Books queryBookByName(String bookName){
return bookMapper.queryBookByName(bookName);
}
}
controller
视图发出请求到controller,controller处理相关请求并返回结果
package controller;
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.RequestMapping;
import pojo.Books;
import service.BookService;
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("/RBook")
public String RBook()
{
return "AddBook";
}
//添加书籍请求
@RequestMapping("/AddBook")
public String AddBook(Books books)
{
//Books books1=new Books(books.getBookName(),books.getBookCounts(),books.getDetail());
bookService.addBook(books);
/*这里return:AllBook 返回的页面无法显示数据
* redirect:/book/AllBook 采用重定向方式可以携带数据
* 重定向是跳到allbook请求*/
return "redirect:/book/AllBook";
}
//跳转到修改书籍页面,注意这里代码
@RequestMapping("/ToUpdate")
public String ToUpdate(int id,Model model)
{
Books books=bookService.queryBookById(id);
model.addAttribute("NewBook",books);
return "UpdateBook";
}
//修改书籍请求
@RequestMapping("/UpdateBook")
public String UpdateBook(Books books)
{
bookService.updateBook(books);
return "redirect:/book/AllBook";
}
//删除书籍请求
@RequestMapping("/DeleteBook")
public String DeleteBook(int id)
{
bookService.deleteBookById(id);
return "redirect:/book/AllBook";
}
//搜索功能
@RequestMapping("/QueryBook")
public String QueryBook(String queryName,Model model)
{
Books books=bookService.queryBookByName(queryName);
List<Books> list = new ArrayList<Books>();
list.add(books);
if(books==null)
{
list=bookService.queryAllBook();
}
model.addAttribute("list",list);
return "AllBook";
}
}
jsp页面
index.jsp
<%--
Created by IntelliJ IDEA.
User: 86183
Date: 2021/8/21
Time: 23:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/book/AllBook">进入全部书籍查询页面</a>
</body>
</html>
AddBook.jsp
<%--
Created by IntelliJ IDEA.
User: 86183
Date: 2021/8/23
Time: 20:32
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/book/AddBook">
书籍ID <input type="text" name="bookID" required>
书籍名字<input type="text" name="bookName" required>
书籍数量<input type="text" name="bookCounts" required>
书籍描述<input type="text" name="detail" required>
<input type="submit" value="提交">
</form>
</body>
</html>
AllBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: 86183
Date: 2021/8/22
Time: 0:27
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
<style>
td{
font-size: 15px;
display: block;
float: left;
width: 100px;
margin-right: 50px;
border: 1px solid black;
}
a{
text-decoration: none;
}
</style>
</head>
<body>
<form action="${pageContext.request.contextPath}/book/QueryBook" method="post">
<input type="text" placeholder="请输入要查询书籍的名字" name="queryName">
<input type="submit" value="查询">
</form>
<table>
<tr>
<td>bookID</td>
<td>bookName</td>
<td>bookCounts</td>
<td>detail</td>
</tr>
<tr>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td style="width:100px"><a href="${pageContext.request.contextPath}/book/ToUpdate?id=${book.bookID}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/DeleteBook?id=${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tr>
</table>
<a href="${pageContext.request.contextPath}/book/RBook">新增书籍</a>
</body>
</html>
NewBook,jsp
<%--
Created by IntelliJ IDEA.
User: 86183
Date: 2021/8/24
Time: 21:44
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<table>
<tr>
<td>bookID</td>
<td>bookName</td>
<td>bookCounts</td>
<td>detail</td>
</tr>
<tr>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
</tr>
</c:forEach>
</tr>
</table>
</body>
</html>
UpdateBook.jsp
<%--
Created by IntelliJ IDEA.
User: 86183
Date: 2021/8/24
Time: 20:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改书籍</title>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/book/UpdateBook">
书籍ID <input type="text" name="bookID" value="${NewBook.bookID}" required>
书籍名字<input type="text" name="bookName" value="${NewBook.bookName}" required>
书籍数量<input type="text" name="bookCounts" value="${NewBook.bookCounts}" required>
书籍描述<input type="text" name="detail" value="${NewBook.detail}" required>
<input type="submit" value="提交">
</form>
</body>
</html>