学习视频来自于:秦疆(遇见狂神说)Bilibili地址
他的自学网站:kuangstudy
保持热爱、奔赴山河
知识要求
需要熟练掌握MySQL数据库(建表+CRUD),Spring、SpringMVC、JavaWeb、MyBatis、html、css、JavaScript、Jquery。
创建一个存放书籍数据的数据库表
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,'从进门到进牢');
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.10version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.7version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.29version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.11version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.3.22version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.3.22version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.9.9.1version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>javax.servlet.jsp-apiartifactId>
<version>2.3.3version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
druid.driverClassName=com.mysql.cj.jdbc.Driver
druid.url=jdbc:mysql://localhost:3306/ssmbuild?userUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT%2B8
druid.username=root
druid.password=root
IDEA关联数据库(关联后写mapper方便一些,不关联也能开发)

编写MyBatis的核心配置文件:mybatis-config.xml
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="pers.tianyu.pojo"/>
typeAliases>
<mappers>
<package name="pers.tianyu.dao"/>
mappers>
configuration>
package pers.tianyu.pojo;
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
/**
*有参/无参构造方法
*set/get方法
*toString方法
**/
}
package pers.tianyu.dao;
import pers.tianyu.pojo.Books;
import java.util.List;
public interface BookMapper {
// 增加一个Book
int addBook(Books book);
// 根据id删除一个Book,@Param("id"):可以为参数指别名
int deleteBookById(@Param("bookID") int id);
// 更新Book
int updateBook(Books book);
// 根据id查询,返回Books
Books queryBookById(@Param("bookID") int id);
// 查询全部Book,返回list集合
List<Books> queryAllBook();
// 根据名字查询书籍
List<Books> queryBookByName(@Param("bookName") String bookName);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="pers.tianyu.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" parameterType="_int">
select bookID, bookName, bookCounts, detail
from ssmbuild.books
where bookID = #{bookID}
select>
<select id="queryAllBook" resultType="books">
select bookID, bookName, bookCounts, detail
from ssmbuild.books
select>
<select id="queryBookByName" resultType="books">
select bookID, bookName, bookCounts, detail
from ssmbuild.books
where bookName like "%"#{bookName}"%"
select>
mapper>
package pers.tianyu.service;
import pers.tianyu.pojo.Books;
import java.util.List;
public interface BookService {
// 增加一个Book
int addBook(Books book);
// 根据id删除一个Book
int deleteBookById(int id);
// 更新Book
int updateBook(Books book);
// 根据id查询,返回Books
Books queryBookById(int id);
// 查询全部Book,返回list集合
List<Books> queryAllBook();
// 根据名字查询书籍
List<Books> queryBookByName(String bookName);
}
实现类:pers.tianyu.service.BookServiceImpl
package pers.tianyu.service;
import pers.tianyu.dao.BookMapper;
import pers.tianyu.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
// 调用dao层的操作,设置一个set接口,方便调用
private BookMapper bookMapper;
public void setBookMapper(BookMapper 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 book) {
return bookMapper.updateBook(book);
}
@Override
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
@Override
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
@Override
public List<Books> queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
}
<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="classpath:database.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${druid.driverClassName}"/>
<property name="url" value="${druid.url}"/>
<property name="username" value="${druid.username}"/>
<property name="password" value="${druid.password}"/>
bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="pers.tianyu.dao"/>
bean>
beans>
<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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="pers.tianyu.service"/>
<bean class="pers.tianyu.service.BookServiceImpl" id="bookService">
<property name="bookMapper" ref="bookMapper"/>
bean>
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice transaction-manager="transactionManager" id="txAdvice">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* pers.tianyu.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
aop:config>
beans>

<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>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>HiddenHttpMethodFilterfilter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<session-config>
<session-timeout>15session-timeout>
session-config>
web-app>
<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">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="pers.tianyu.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
<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">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:springmvc-servlet.xml"/>
beans>
项目结构

package pers.tianyu.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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pers.tianyu.pojo.Books;
import pers.tianyu.service.BookService;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
private BookService bookService;
@Autowired
@Qualifier(value = "bookService")
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
}
//查询全部书籍信息,并返回到一个书记展示页面
@RequestMapping("/allBook")
public String list(Model model) {
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
DOCTYPE HTML>
<head>
<title>首页title>
<style>
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>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<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>
<%--row clearfix表示不受其他样式控制,清除浮动--%>
<div class="container">
<div class="row clearfix">
<div class="clo-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">
<%--查询书籍--%>
<span style="color: red";font-weight:bold>
${msg}
span>
<form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post">
<input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询书籍的名称">
<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>
<%--书籍从数据库中查询出来,从这个List中遍历出来: foreach--%>
<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/${book.bookID}">修改a><br>
<a href="${pageContext.request.contextPath}/book/del/${book.bookID}">删除a>
td>
tr>
c:forEach>
tbody>
table>
div>
div>
div>
body>
html>
//跳转添加页面
@RequestMapping("/toAddBook")
public String toAddPaper(){
return "addBook";
}
//添加书籍信息
@RequestMapping("/addBook")
public String addPage(Books books){
bookService.addBook(books);
return "redirect:/book/allBook";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<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}/book/addBook" method="post">
<div class="form-group">
<label for="bkname">书籍名称:label>
<input type="text" name="bookName" id="bkname" required /><br><br><br>
div>
<div class="form-group">
<label for="bkcounts">书记数量:label>
<input type="text" name="bookCounts" id="bkcounts" required /><br><br><br>
div>
<div class="form-group">
<label for="bkdetail">书记详情:label>
<input type="text" name="detail" id="bkdetail" required /><br><br><br>
div>
<input type="submit" value="添加">
form>
div>
body>
html>
//删除书籍 RestFull风格
@RequestMapping("/del/{bookID}")
private String deleteBook(@PathVariable("bookID") int id){
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
//修改前信息回显 RestFull风格
@RequestMapping("/toUpdateBook/{bookID}")
public String toUpdateBook(Model model,@PathVariable("bookID") int id){
Books books = bookService.queryBookById(id);
model.addAttribute("book",books);
return "updateBook";
}
//修改书籍信息
@RequestMapping("/updateBook")
public String updateBook(Model model,Books books){
bookService.updateBook(books);
return "redirect:/book/allBook";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<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}/book/updateBook" method="post">
<input type="hidden" name="bookID" value="${book.getBookID()}"/>
<div class="form-group">
<label for="bkname">书籍名称:label>
<input type="text" name="bookName" id="bkname" value="${book.getBookName()}" required /><br><br><br>
div>
<div class="form-group">
<label for="bkcounts">书记数量:label>
<input type="text" name="bookCounts" id="bkcounts" value="${book.getBookCounts()}" required /><br><br><br>
div>
<div class="form-group">
<label for="bkdetail">书记详情:label>
<input type="text" name="detail" id="bkdetail" value="${book.getDetail()}" required /><br><br><br>
div>
<input type="submit" value="保存"/>
form>
div>
body>
html>
// 查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
List<Books> list = bookService.queryBookByName(queryBookName);
if(list.isEmpty()){
model.addAttribute("msg","未查到");
}else {
model.addAttribute("list",list);
}
return "allBook";
}