SpringMVC 学习(八)整合SSM

10. 整合 SSM

(1) 新建数据库

在这里插入图片描述

CREATE DATABASE `SSM`;

USE `SSM`;

DROP TABLE IF EXISTS `BOOKS`;

CREATE TABLE `BOOKS` (
  `BOOK_ID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书ID',
  `BOOK_NAME` VARCHAR(100) NOT NULL COMMENT '书名',
  `BOOK_COUNTS` INT(11) NOT NULL COMMENT '数量',
  `DETAIL` VARCHAR(200) NOT NULL COMMENT '描述',
  KEY `BOOK_ID` (`BOOK_ID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT  INTO `BOOKS`(`BOOK_ID`,`BOOK_NAME`,`BOOK_COUNTS`,`DETAIL`)VALUES 
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');

(2) 新建 maven 项目

在这里插入图片描述

1) 导入依赖

<!--依赖-->
<dependencies>
    
    <!--junit : 单元测试-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>

    <!--数据库连接驱动 : java 连接 mysql-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version>
    </dependency>
    <!--c3p0 : 数据库连接池,避免重复连接数据库,缓冲作用-->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.5</version>
    </dependency>

    <!--servlet-api : servlet 编写编译支持-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <!--仅开发时使用,不进行打包处理-->
        <scope>provided</scope>
    </dependency>
    <!--jsp-api : jsp 编译支持-->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.3</version>
        <scope>provided</scope>
    </dependency>
    <!--jstl : JSP 标准标签库-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

    <!--mybatis -->
    <!--mybatis 标准库-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    <!--spring 整合 mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>

    <!--spring-->
    <!--Spring MVC 支持-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.9</version>
    </dependency>
    <!--jdbc : 连接、请求数据库,处理返回结果-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.9</version>
    </dependency>
    
    <!--lombok : 偷懒神器-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
    </dependency>
    
</dependencies>

2) 静态资源过滤

<!--静态资源导出问题-->
<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>

(3) IDEA 连接数据库

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

(4) Spring 整合 Mybatis

1) 新建包结构

在这里插入图片描述

2) 新建配置文件

在这里插入图片描述

● spring

配置文件名称 : 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">
</beans>
● 创建 spring 应用上下文

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

应用上下文关联了所有的 spring 配置文件,最好保证所有的配置文件都在其中。

● mybatis

配置文件名 : 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>
</configuration>

3) 新建实体类

● 开启驼峰命名自动映射

配置路径:resources/com/why/dao/ mybatis-config.xml

<settings>
    <!--开启驼峰命名的自动映射-->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
    <!--开启标准日志-->
    <!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
</settings>
● 开启别名映射

配置路径:resources/com/why/dao/ mybatis-config.xml

<!--别名-->
<typeAliases>
    <!--扫描包-->
    <package name="com.why.pojo"/>
</typeAliases>
● 编写实体类
package com.why.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * TODO
 * Books 实体类
 * @author why
 * @since 2021/9/16 10:59
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {

    private Integer bookId;

    private String bookName;

    private Integer bookCounts;

    private String detail;

}

在这里插入图片描述

4) 新建映射器接口

在这里插入图片描述

package com.why.dao;

import com.why.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * TODO
 * Book 映射器
 * @author why
 * @since 2021/9/16 13:20
 */
public interface BookMapper {

    /**
     * 增加一本书
     * @param book Books 对象
     * @return Integer 结果
     */
    Integer addBook(Books book);

    /**
     * 根据书 ID 删除一本书
     * @param id 书 ID
     * @return Integer 结果
     */
    Integer deleteBookById(@Param("bookId") Integer id);

    /**
     * 更新一本书
     * @param book Books 对象
     * @return Integer 结果
     */
    Integer updateBook(Books book);

    /**
     * 根据书 ID 查询一本书
     * @param id 书 ID
     * @return Books 结果
     */
    Books queryBookById(@Param("bookId") Integer id);

    /**
     * 查询全部书
     * @return List 结果
     */
    List<Books> queryAllBook();

}

5) 新建映射器 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.why.dao.BookMapper">

    <insert id="addBook" parameterType="Books">
        insert into ssm.books (BOOK_NAME, BOOK_COUNTS, DETAIL) values (#{bookName}, #{bookCounts}, #{detail});
    </insert>

    <!--int 会自动转换为 Intager,_int 才是 int-->
    <delete id="deleteBookById" parameterType="int">
        delete from ssm.books where BOOK_ID = #{bookId};
    </delete>

    <update id="updateBook" parameterType="Books">
        update ssm.books
        set BOOK_NAME = #{bookName}, BOOK_COUNTS = #{bookCounts}, DETAIL = #{detail}
        where BOOK_ID = #{bookId};
    </update>

    <select id="queryBookById" resultType="Books">
        select * from ssm.books where BOOK_ID = #{bookId};
    </select>

    <select id="queryAllBook" resultType="Books">
        select * from ssm.books;
    </select>

</mapper>

6) 注册映射器接口

注册路径:resources/com/why/dao/ mybatis-config.xml

<mappers>
    <mapper class="com.why.dao.BookMapper"/>
</mappers>

7) 编写服务层

在这里插入图片描述

● 服务接口
package com.why.service;

import com.why.pojo.Books;

import java.util.List;

/**
 * TODO
 * Book 服务接口
 * @author why
 * @since 2021/9/16 14:03
 */
public interface BookService {

    /**
     * 增加一本书
     * @param book Books 对象
     * @return Integer 结果
     */
    Integer addBook(Books book);

    /**
     * 根据书 ID 删除一本书
     * @param id 书 ID
     * @return Integer 结果
     */
    Integer deleteBookById(Integer id);

    /**
     * 更新一本书
     * @param book Books 对象
     * @return Integer 结果
     */
    Integer updateBook(Books book);

    /**
     * 根据书 ID 查询一本书
     * @param id 书 ID
     * @return Books 结果
     */
    Books queryBookById(Integer id);

    /**
     * 查询全部书
     * @return List 结果
     */
    List<Books> queryAllBook();

}
● 服务实现类
package com.why.service.Impl;

import com.why.dao.BookMapper;
import com.why.pojo.Books;
import com.why.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * TODO
 * Book 服务实现类
 * @author why
 * @since 2021/9/16 14:05
 */
public class BookServiceImpl implements BookService {

    private BookMapper bookMapper;
    
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    public Integer addBook(Books book) {
        return bookMapper.addBook(book);
    }

    public Integer deleteBookById(Integer id) {
        return bookMapper.deleteBookById(id);
    }

    public Integer updateBook(Books book) {
        return bookMapper.updateBook(book);
    }

    public Books queryBookById(Integer id) {
        return bookMapper.queryBookById(id);
    }

    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }

}

8) spring 整合 dao 层

● 编写数据库配置文件

在这里插入图片描述

jdbc.driver=com.mysql.jdbc.Driver
# MySQL 8.0+ 需配置时区:&serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=981030
● 新建 spring 配置文件

在这里插入图片描述

<?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">

</beans>
● 加入到 spring 应用上下文

在这里插入图片描述
在这里插入图片描述

● 关联数据库配置文件
  • 引入 context 约束

    xmlns:context="http://www.springframework.org/schema/context"
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    

    在这里插入图片描述

  • 此处也可用 IDEA 自动引入,但引入的为 c 空间和 p 空间约束,编写代码无提示。

    在这里插入图片描述

    在这里插入图片描述

    配置数据库配置文件路径

    <!--1. 关联数据库配置文件-->
    <context:property-placeholder location="classpath:database.properties"/>
    
● 配置数据库连接池
<!--2. 配置数据库连接池-->
<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>
● 创建 sqlSessionFactory
<!--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>
● 配置 dao 层映射器扫描包

此处配置可理解为由 Spring 完成 Mybatis 中 getSqlSession 操作

<!--4. 配置 dao 接口扫描包,动态地将 dao 接口注册进入 spring 容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!--注入 sqlSessionFactory-->
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <!--配置 dao 包路径-->
    <property name="basePackage" value="com.why.dao"/>
</bean>
● 引入到 applicationContext.xml

引入路径:resources/ applicationContext.xml

<import resource="classpath:spring-dao.xml"/>

9) spring 整合 service 层

● 新建 spring 配置文件
<?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">

</beans>
● 将配置文件加入到 spring 上下文

在这里插入图片描述

● 扫描 service 包
<!--1. 扫描 service 包-->
<context:component-scan base-package="com.why.service"/>
● 将业务类注入到 spring 容器
<!--
    2. 将业务类注入到 spring 容器
    BookServiceImpl.bookMapper 必须有 set 方法
    BookService.bookMapper 在 spring-dao.xml 中扫描 dao 包时注入到 spring 中了
-->
<bean id="bookMapperImpl" class="com.why.service.impl.BookServiceImpl">
    <property name="bookMapper" ref="bookMapper"/>
</bean>
//注解实现:
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    ...
}
● 声明式事务配置
<!--3. 声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--注入数据源-->
    <property name="dataSource" ref="dataSource"/>
</bean>
● 引入到 applicationContext.xml

引入路径:resources/ applicationContext.xml

10) 测试

<import resource="classpath:spring-service.xml"/>
● 新建测试类

在这里插入图片描述

package com.why;

import com.why.pojo.Books;
import com.why.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * TODO
 * 测试类
 * @author why
 * @since 2021/9/16 20:12
 */
public class MyTest {

    @Test
    public void testAllBooks() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println(context);
        BookService bookService = (BookService) context.getBean("bookServiceImpl");
        System.out.println(bookService);
        List<Books> books = bookService.queryAllBook();
        for (Books book : books) {
            System.out.println(book);
        }
    }
}
● 运行测试函数

在这里插入图片描述

Mybatis 整合完毕!!!

(5) 整合 Spring MVC

1) 添加 web 支持

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

2) 新建 Spring MVC 配置文件

在这里插入图片描述

<?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">

</beans>
● 引入 mvc 约束
xmlns:mvc="http://www.springframework.org/schema/mvc"
...
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd

在这里插入图片描述

● 引入 context 约束
xmlns:context="http://www.springframework.org/schema/context"
...
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd

在这里插入图片描述

● 注解驱动
<!--1. 注解驱动-->
<mvc:annotation-driven/>
● 静态资源过滤
<!--2. 静态资源过滤-->
<mvc:default-servlet-handler/>
● 扫描 controller
<!--3. 扫描包-->
<context:component-scan base-package="com.why.controller"/>
● 视图解析器
<!--4. 视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>
● 引入到 applicationContext.xml

引入路径:resources/ `applicationContext.xml

<import resource="classpath:spring-mvc.xml"/>

3) 编写 web.xml

● 注册 DispatcherServlet
<!--1. DispatcherServlet-->
<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <!--注意 : 此处需要引入 spring 的整体应用配置文件-applicationContext.xml-->
        <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>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
<!--Session-->
<session-config>
    <session-timeout>15</session-timeout>
</session-config>

4) 测试

● 编写 index.jsp
<%--
  User: why
  Date: 2021/9/16
  Time: 17:03
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
  </head>
  <body>
    <h3>
      <a href="${pageContext.request.contextPath}/book/allBooks">进入书籍页面</a>
    </h3>
  </body>
</html>
● 新建测试页面

在这里插入图片描述

<%--
  User: why
  Date: 2021/9/16
  Time: 20:02
--%>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>All Books</title>

    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</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 clearfix">
            <div class="col-md-12 column">
                <table class="table table-hover table-striped">
                    <thead>
                        <tr>
                            <th>编号</th>
                            <th>数量</th>
                            <th>数量</th>
                            <th>详情</th>
                        </tr>
                    </thead>
                    <tbody>
                        <%--items 的值是控制器中 model.addAttribute("books", books); 的关键字 "books" --%>
                        <c:forEach var="book" items="${books}">
                            <tr>
                                <td>${book.bookId}</td>
                                <td>${book.bookName}</td>
                                <td>${book.bookCounts}</td>
                                <td>${book.detail}</td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
● 新建控制器

在这里插入图片描述

package com.why.controller;

import com.why.pojo.Books;
import com.why.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.RequestMapping;

import java.util.List;

/**
 * TODO
 * Book 控制器
 * @author why
 * @since 2021/9/16 19:51
 */
@Controller
@RequestMapping("/book")
public class BookController {


    // 自动装配
    @Autowired
    // 指定一个 bean (bookServiceImpl)为 bookService 属性进行装配,可省略
    @Qualifier("bookServiceImpl")
    private BookService bookService;

    @RequestMapping("/allBooks")
    public String allBooks(Model model) {
        List<Books> books = bookService.queryAllBook();
        model.addAttribute("books", books);
        return "allBooks";
    }

}
● 发布项目中导入依赖

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

● 添加服务器

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

● 运行服务器

在这里插入图片描述

在这里插入图片描述

Spring MVC 整合完毕!!!

(6) 整合测试

在这里插入图片描述

(7) CRUD

1) 增加

● 添加界面元素
<div class="col-md-1 column">
    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">
        <%--添加--%>
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-plus-lg" viewBox="0 0 16 16">
            <path d="M8 0a1 1 0 0 1 1 1v6h6a1 1 0 1 1 0 2H9v6a1 1 0 1 1-2 0V9H1a1 1 0 0 1 0-2h6V1a1 1 0 0 1 1-1z"/>
        </svg>
    </a>
</div>
● 添加跳转控制器
@RequestMapping("/toAddBook")
public String toAddBook() {
    return "addBook";
}
● 新建增加界面

在这里插入图片描述

<%--
  Created by IntelliJ IDEA.
  User: LENOVO
  Date: 2021/9/17
  Time: 19:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Add Book</title>

    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</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="name">书名</label>
                <%--name 属性值与实体类属性同名--%>
                <input type="text" class="form-control" id="name" name="bookName" required>
            </div>
            <div class="form-group">
                <label for="counts">数量</label>
                <input type="text" class="form-control" id="counts" name="bookCounts" required>
            </div>
            <div class="form-group">
                <label for="detail">描述</label>
                <input type="text" class="form-control" id="detail" name="detail" required>
            </div>
            <button type="submit" class="btn btn-primary">添加</button>
        </form>

    </div>

</body>
</html>

在这里插入图片描述

● 添加增加书籍控制器
@RequestMapping("/addBook")
public String addBook(Books book) {
    System.out.println("addBook.book => "+book);
    Integer addRes = bookService.addBook(book);
    System.out.println("addRes => " + addRes);
    return "redirect:/book/allBooks";
}

2) 删除

● 添加界面元素
<th>操作</th>
...
<td>
    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/deleteBook/${book.bookId}">
        <%--删除--%>
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x-square" viewBox="0 0 16 16">
            <path d="M14 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h12zM2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2z"/>
            <path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
        </svg>
    </a>
</td>
● 添加删除控制器
@RequestMapping("/deleteBook/{id}")
public String deleteBook(@PathVariable("id") Integer id) {
    Integer deleteRes = bookService.deleteBookById(id);
    System.out.println("deleteRes => " + deleteRes);
    return "redirect:/book/allBooks";
}

3) 修改

● 添加界面元素
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toUpdate?id=${book.bookId}">
<%--修改--%>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-square" viewBox="0 0 16 16">
<path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z"/>
<path fill-rule="evenodd" d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z"/>
</svg>
</a>
● 添加跳转控制器
@RequestMapping("/toUpdate")
public String toUpdate(Integer id, Model model) {
    Books book = bookService.queryBookById(id);
    System.out.println("toUpdate.book => "+book);
    model.addAttribute("book", book);
    return "updateBook";
}
● 添加修改界面

在这里插入图片描述

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Update Book</title>

    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</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">
        <div class="form-group">
            <label for="id">编号</label>
            <%--
                type 为隐藏域
                name 属性值与实体类属性同名
                从toUpdatePage 控制器取出 value 属性值
            --%>
            <input type="text" class="form-control" id="id" name="bookId" value="${book.bookId}" readonly>
        </div>
        <div class="form-group">
            <label for="name">书名</label>
            <input type="text" class="form-control" id="name" name="bookName" value="${book.bookName}" required>
        </div>
        <div class="form-group">
            <label for="counts">数量</label>
            <input type="text" class="form-control" id="counts" name="bookCounts" value="${book.bookCounts}" required>
        </div>
        <div class="form-group">
            <label for="detail">描述</label>
            <input type="text" class="form-control" id="detail" name="detail" value="${book.detail}" required>
        </div>
        <button type="submit" class="btn btn-primary">修改</button>
    </form>

</div>

</body>
</html>

在这里插入图片描述

● 添加修改控制器
@RequestMapping("/updateBook")
public String updateBook(Books book) {
    System.out.println("updateBook.book => "+book);
    Integer updateRes = bookService.updateBook(book);
    System.out.println("updateRes => " + updateRes);
    return "redirect:/book/allBooks";
}

4) 查询

● 添加界面元素
<div class="col-md-10">
    <form action="${pageContext.request.contextPath}/book/queryBookByName" method="post">
        <div class="input-group">
            <%--name 属性值与 Controller 参数名一致--%>
            <input type="text" name="name" class="form-control" placeholder="请输入书籍名称" required>
            <span class="input-group-btn">
                <button class="btn btn-default" type="submit" id="search">
                    <%--搜索--%>
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-search" viewBox="0 0 20 20">
                        <path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/>
                    </svg>
                </button>
            </span>
        </div>
    </form>
</div>

<div class="col-md-1 column">
    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBooks">
        <%--显示全部书籍--%>
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-layout-text-sidebar-reverse" viewBox="0 0 16 16">
            <path d="M12.5 3a.5.5 0 0 1 0 1h-5a.5.5 0 0 1 0-1h5zm0 3a.5.5 0 0 1 0 1h-5a.5.5 0 0 1 0-1h5zm.5 3.5a.5.5 0 0 0-.5-.5h-5a.5.5 0 0 0 0 1h5a.5.5 0 0 0 .5-.5zm-.5 2.5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1 0-1h5z"/>
            <path d="M16 2a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2zM4 1v14H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h2zm1 0h9a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H5V1z"/>
        </svg>
    </a>
</div>
...
<%--警告提示框--%>
<c:if test="${error!=null}">
    <div id="alert" class="alert alert-warning">
        <a href="#" class="close" data-dismiss="alert">&times;</a>
        <strong>${error}</strong>
    </div>
</c:if>

<%--关闭警告框--%>
<script>
    $(function(){
        $(".close").click(function(){
            $("#alert").alert();
        });
    });
</script>
● 添加查询控制器
@RequestMapping("/queryBookByName")
public String queryBookByName(String name, Model model) {
    System.out.println("queryBookByName.name => " + name);
    if (name == null || name.equals("")) {
        return "redirect:/book/allBooks";
    }
    List<Books> books = bookService.queryBookByName(name);
    System.out.println("queryBookByName.books.size => " + books.size());
    if (books.size() == 0) {
        String error = "警告!没有查询到此书籍。";
        model.addAttribute("error", error);
        books = bookService.queryAllBook();
    }
    model.addAttribute("books", books);
    return "allBooks";
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值