目录
环境: IDEA jdk 1.8 MySQL 5.7.19 Tomcat 9 Maven 3.6
项目代码: https://github.com/duxuan11/ssmbuild
需求分析
1.显示所有书籍 2.新增书籍 3.修改书籍 4.删除书籍 5.按书名查找书籍
项目效果:
项目结构
逻辑顺序
数据库
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,'从进门到进牢'),
(4,'C++',20,'赶快放弃'),
(5,'Linux',12,'搞不懂');
Mybats
pojo/Books
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/BookMapper
package com.duxuan.dao;
import com.duxuan.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.awt.print.Book;
import java.util.List;
public interface BookMapper {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(@Param("bookId") int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(int id);
//查询全部的书
List<Books> queryAllBooks();
//通过名称查询书籍
List<Books> queryBookByName(@Param("bookName") String bookName);
}
dao/Mapper.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="com.duxuan.dao.BookMapper">
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books (bookName, bookCounts, detail)
values (#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBookById" 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="queryAllBooks" resultType="Books">
select * from ssmbuild.books
</select>
<select id="queryBookByName" resultType="Books">
select * from ssmbuild.books where bookName=#{bookName};
</select>
</mapper>
Spring
datebase.properties
#如果使用的是MySQL8.0+,增加一个时区的设置
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
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"></context:property-placeholder>
<!--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的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--有这个就再也不用写dao的impl实现类了-->
</bean>
<!--4.配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中! String类型用value-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的dao包-->
<property name="basePackage" value="com.duxuan.dao"/>
</bean>
</beans>
service/BookService
package com.duxuan.service;
import com.duxuan.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(@Param("bookId") int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(int id);
//查询全部的书
List<Books> queryAllBooks();
//通过名称查询书籍
List<Books> queryBookByName(@Param("bookName") String bookName);
}
service/BookServiceImpl
package com.duxuan.service;
import com.duxuan.dao.BookMapper;
import com.duxuan.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("BookServiceImpl")
public class BookServiceImpl implements BookService {
//service调dao层 组合Dao
@Autowired
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBooks() {
return bookMapper.queryAllBooks();
}
public List<Books> queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
}
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">
<!--获取上下文 就不用Import了-->
<!--1.扫描service下的包-->
<context:component-scan base-package="com.duxuan.service"/>
<!--2.将我们的所有的业务类,注入到Spring,可以通过配置,或者注解实现 这里注解和xml都使用了-->
<bean id="BookServiceImpl" class="com.duxuan.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>
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-service.xml"/>
<import resource="spring-dao.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
SpringMVC
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">
<!--SpringMVC 1.dispatcherServlet-->
<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>
<!--2.乱码过滤-->
<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>
<!--Session-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
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.duxuan.controller"/>
<!--4.视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
controller/BookController
package com.duxuan.controller;
import com.duxuan.pojo.Books;
import com.duxuan.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 {
//controller调service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询全部的书籍,并且返沪hi到一个书籍展示页面
@RequestMapping("/allBook")
public String list(Model model){
List<Books> list = bookService.queryAllBooks();
model.addAttribute("list",list);
return "allBook"; //返回allBook页面
}
//跳转到增加书籍页面
@RequestMapping("/toAddBook")
public String toAddPager(){
return "addBook";
}
//添加书籍的请求
@RequestMapping("/addBook")
public String addBook(Books books){
System.out.println("addBook=" + books);
bookService.addBook(books);
return "redirect:/book/allBook"; //重定向我们allbook实现请求复用,让其跳到上面的方法里
}
//跳转到修改页面
@RequestMapping("/toUpdateBook/{id}")
public String toUpdatePaper(@PathVariable int id,Model model){
Books books = bookService.queryBookById(id);
model.addAttribute("QBbooks",books);
model.addAttribute("id",id);
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Books books,Model model){
System.out.println("修改了"+books);
bookService.updateBook(books);
return "redirect:/book/allBook";
}
@RequestMapping("/deleteBook/{id}")
public String deleteBook(@PathVariable int id,Model model){
System.out.println("删除了"+id);
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
//查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
List<Books> list = bookService.queryBookByName(queryBookName);
if (list.isEmpty()){
list = bookService.queryAllBooks();
model.addAttribute("error","未查到");
}
model.addAttribute("list",list);
return "allBook"; //返回allBook页面
}
}
前端
index.jsp
<%--
Created by IntelliJ IDEA.
User: ASUS
Date: 2022/2/19
Time: 22:20
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style>
a{
text-decoration: none;
color: black;
font-size: 18px;
}
h3{
width: 100px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 5px;
}
</style>
</head>
<body>
<a href="${pageContext.request.contextPath}/book/allBook">进入书籍展示页面</a>
</body>
</html>
WEB-INF/jsp/allbook
<%--
Created by IntelliJ IDEA.
User: ASUS
Date: 2022/2/20
Time: 20:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<%--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">
书籍名称:<input type="text" name="bookName" required><br><br><br>
书籍数量:<input type="text" name="bookCounts" required><br><br><br>
书籍详情:<input type="text" name="detail" required><br><br><br>
<input type="submit" value="添加">
</form>
</div>
</body>
</html>
WEB-INF/jsp/addbook
<%--
Created by IntelliJ IDEA.
User: ASUS
Date: 2022/2/20
Time: 20:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<%--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">
书籍名称:<input type="text" name="bookName" required><br><br><br>
书籍数量:<input type="text" name="bookCounts" required><br><br><br>
书籍详情:<input type="text" name="detail" required><br><br><br>
<input type="submit" value="添加">
</form>
</div>
</body>
</html>
WEB-INF/jsp/updatebook
<%--
Created by IntelliJ IDEA.
User: ASUS
Date: 2022/2/20
Time: 20:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改书籍</title>
<%--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">
<%--出现的问题,我们提交了修改的SQL请求,但是修改失败--初次考虑,是事务问题,配置完毕,依旧失败!--%>
<%--看一下SQL语句,能否执行成功,SQL执行失败,修改未完成--%>
<%--传递隐藏域--%>
<input type="hidden" name="bookID" value="${QBbooks.bookID}">
书籍名称:<input type="text" name="bookName" value="${QBbooks.bookName}"><br><br><br>
书籍数量:<input type="text" name="bookCounts" value="${QBbooks.bookCounts}"><br><br><br>
书籍详情:<input type="text" name="detail" value="${QBbooks.detail}"><br><br><br>
<input type="submit" value="添加">
</form>
</div>
</body>
</html>