Sprig framework integration (SSM framework) | Sping+SpringMVC+Mybatis

SSM framework

insert image description here

SSM is the integrated framework of spring+springMVC+mybatis: standard MVC mode, the whole system is divided into four layers: presentation layer, controller layer, service layer, and DAO layer

  • Spring (business layer)

    Spring is like a large factory for assembling beans in the entire project. In the configuration file, you can specify specific parameters to call the constructor of the entity class to instantiate the object. It can also be called the glue in the project.

    The core idea of ​​Spring is IoC (Inversion of Control), that is, programmers are no longer required to explicitly newcreate an object, but let the Spring framework do it all for you.

  • SpringMVC (presentation layer)

    SpringMVC intercepts user requests in the project. Its core Servlet, DispatcherServlet, assumes the role of intermediary or front desk, and matches user requests with the Controller through HandlerMapping. The Controller is the specific operation performed by the corresponding request. SpringMVC is equivalent to struts in the SSH framework.

  • Mybatis (persistence layer)

    mybatis is an encapsulation of jdbc, which makes the underlying operation of the database transparent. The operations of mybatis revolve around a sqlSessionFactory instance. Mybatis is associated to the Mapper file of each entity class through the configuration file. The Mapper file configures the SQL statement mapping required by each class to the database. Every time you interact with the database, get a sqlSession through sqlSessionFactory, and then execute the sql command.

    The page sends a request to the controller, the controller invokes the business layer processing logic, the logic layer sends a request to the persistence layer, the persistence layer interacts with the database, and returns the result to the business layer, the business layer sends the processing logic to the controller, and the controller then Call the view to display the data

project structure

insert image description here

SSM integration

Mybatis layer

configuration

  • Database environment configuration
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, '从进门到进牢');
  • pom.xml configuration
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SSMBuild</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <!--依赖导入-->
    <dependencies>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <!--数据库连接池-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <!--Servlet - JSP -->
        <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>

        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <!--Lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
    </dependencies>

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

resources package

  • mybatis-config.xml (mybatis core configuration file)
<?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操作-->

    <!--typeAliases:它仅用于XML配置,意在降低冗余的全限定类名书写-->
    <typeAliases>
        <package name="com.wei.pojo"/>
    </typeAliases>

    <!-- 使用映射器接口实现类的完全限定类名 -->
    <mappers>
        <mapper class="com.wei.dao.BookMapper"/>
    </mappers>
</configuration>
  • applicationContext.xml (spring core configuration file)
<?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>
  • database.properties (core configuration file)
jdbc.driver=com.mysql.jdbc.Driver
# 如果使用MYSQL8.0+,需要增加时区配置;&serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root

java package

  • com.wei.pojo.Books (the entity class corresponding to the database)
package com.wei.pojo;

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;

}
  • com.wei.dao.BookMapper (write the Mapper interface of the Dao layer)
package com.wei.dao;

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

import java.util.List;

public interface BookMapper {
     
     

    //增加一本书
    int addBook(Books books);

    //删除一本书,@Param注解给参数命名
    int deleteBookById(@Param("bookId") int id);

    //更新一本书
    int updateBook(Books books);

    //查询一本书
    Books queryBookById(@Param("bookId") int id);

    //查询全部书
    List<Books> queryAllBook();
}
  • com.wei.pojo.BooksMapper.xml (write the Mapper.xml mapping file corresponding to the interface, and import the MyBatis package)
<?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.wei.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" parameterType="int" resultType="Books">
        select * from ssmbuild.books where bookID=#{bookID};
    </select>

    <select id="queryAllBook" resultType="Books">
        select * from ssmbuild.books;
    </select>
</mapper>
  • Write the interface of the Service layer
package com.wei.service;

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

import java.util.List;

public interface BookService {
     
     

    //增加一本书
    int addBook(Books books);

    //删除一本书,@Param注解给参数命名
    int deleteBookById(int id);

    //更新一本书
    int updateBook(Books books);

    //查询一本书
    Books queryBookById(int id);

    //查询全部书
    List<Books> queryAllBook();

}
  • Write the implementation class of the Service layer
package com.wei.service;

import com.wei.dao.BookMapper;
import com.wei.pojo.Books;

import java.util.List;

public class BookServiceImpl implements BookService{
     
     

     //调用dao层的操作,设置一个set接口,方便Spring管理
    private BookMapper bookMapper;
    public void setBookMapper(BookMapper bookMapper) {
     
     
        this.bookMapper = bookMapper;
    }

    @Override
    public int addBook(Books books) {
     
     
        return bookMapper.addBook(books);
    }

    @Override
    public int deleteBookById(int id) {
     
     
        return bookMapper.deleteBookById(id);
    }

    @Override
    public int updateBook(Books books) {
     
     
        return bookMapper.updateBook(books);
    }

    @Override
    public Books queryBookById(int id) {
     
     
        return bookMapper.queryBookById(id);
    }

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

Spring layer

resource package

  • spring-dao.xml (spring integrated dao layer)
<?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">

    <!--关联数据库配置文件:Spring读取数据库配置文件-->
    <context:property-placeholder location="classpath:database.properties"/>

    <!--连接池:
    dbcp:半自动化操作,不能自动连接
    c3p0:自动化操作,自动化的加载配置文件,并且可以自动设置到对象中
    druid、hikari-->

    <!--
    dbcp:
    <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=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    -->

    <!--c3p0-->
    <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对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!--配置dao接口扫描包:动态实现Dao接口注入Spring容器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="sqlSessionTemplateBeanName" value="sqlSessionFactory"/>
        <!--要扫描的包-->
        <property name="basePackage" value="com.wei.dao"/>
    </bean>
</beans>
  • spring-service.xml (Spring integrated service layer)
<?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">

    
    <!--扫描service下的包-->
    <context:component-scan base-package="com.wei.service"/>
    
    <!--将所有业务类注入Spring,可以通过配置或者注解-->
    <bean id="BookServiceImpl" class="com.wei.service.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 layer

Add web support

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

    <!--配置DispatcherServlet:SpringMVC的核心:请求分发器,前端控制器-->
    <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>

    <!--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:mvc="http://www.springframework.org/schema/mvc"
       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/cache/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--注解驱动-->
    <mvc:annotation-driven/>
    <!--静态资源-->
    <mvc:default-servlet-handler/>
    <!--扫描包:controller-->
    <context:component-scan base-package="com.wei.controller"/>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </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-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>
    
</beans>

Query book function

  • BookController.java
package com.wei.controller;

import com.wei.dao.BookMapper;
import com.wei.pojo.Books;
import com.wei.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;

@Controller
@RequestMapping("/book")
public class BookController {
     
     
    //controller 调 service 层
    @Autowired
    @Qualifier("BookServiceImpl")   //指定一个唯一的bean对象注入
    private BookService bookService;

    //查询全部数据,并且返回到一个书籍展示页面
    @RequestMapping("/allBook")
    public String list(Model model){
     
     
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list",list);
        return "allBook";
    }
}
  • Home index.jsp
<%--
  Created by IntelliJ IDEA.
  User: ws199
  Date: 2022/11/28
  Time: 14:19
  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;
        }
        h1{
            width: 180px;
            height: 38px;
            margin: 100px auto;
            text-align: center;
            line-height: 38px;
            background: deeppink;
            border-radius: 5px;
        }
    </style>
</head>
<body>

<h1>
  <a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
</h1>

</body>
</html>
  • Book list page allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: ws199
  Date: 2022/11/28
  Time: 15:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>书籍展示</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/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 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>
                <%--书籍从数据库中查询出来,从这个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>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>

add book feature

  • BookController.java
package com.wei.controller;

import com.wei.dao.BookMapper;
import com.wei.pojo.Books;
import com.wei.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;

@Controller
@RequestMapping("/book")
public class BookController {
     
     
    //controller 调 service 层
    @Autowired
    @Qualifier("BookServiceImpl")   //指定一个唯一的bean对象注入
    private BookService bookService;

    //查询全部数据,并且返回到一个书籍展示页面
    @RequestMapping("/allBook")
    public String list(Model model) {
     
     
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list", list);
        return "allBook";
    }

    //跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPaper() {
     
     
        return "addBook";
    }

    //添加书籍的请求
    @RequestMapping("/addBook")
    public String addBook(Books books) {
     
     
        System.out.println("addBook:" + books);
        bookService.addBook(books);
        return "redirect:/book/allBook";       //重定向到@RequestMapping("/allBook")请求
    }
}
  • addBook.jsp add book page
<%--
  Created by IntelliJ IDEA.
  User: ws199
  Date: 2022/12/1
  Time: 14:34
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>添加书籍</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/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>

        <form action="${pageContext.request.contextPath}/book/addBook" method="post">
            <div class="form-group">
                <label>书籍名称:</label>
                <input type="text" name="bookName" class="form-control" required>
            </div>
            <div class="form-group">
                <label>书籍数量:</label>
                <input type="text" name="bookCounts" class="form-control" required>
            </div>
            <div class="form-group">
                <label>书籍描述:</label>
                <input type="text" name="detail" class="form-control" required>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary">添加</button>
            </div>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>

modify book function

  • BookController.java
package com.wei.controller;

import com.wei.dao.BookMapper;
import com.wei.pojo.Books;
import com.wei.service.BookService;
import org.apache.ibatis.annotations.Param;
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 BookController {
     
     
    //controller 调 service 层
    @Autowired
    @Qualifier("BookServiceImpl")   //指定一个唯一的bean对象注入
    private BookService bookService;

    //查询全部数据,并且返回到一个书籍展示页面
    @RequestMapping("/allBook")
    public String list(Model model) {
     
     
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list", list);
        return "allBook";
    }

    //跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPaper() {
     
     
        return "addBook";
    }

    //添加书籍的请求
    @RequestMapping("/addBook")
    public String addBook(Books books) {
     
     
        System.out.println("addBook:" + books);
        bookService.addBook(books);
        return "redirect:/book/allBook";       //重定向到@RequestMapping("/allBook")请求
    }

    //跳转到修改页面
    @RequestMapping("/toUpdate")
    public String toUpdatePaper(int id, Model model){
     
     
        Books books = bookService.queryBookById(id);
        model.addAttribute("books",books);
        return "updateBook";
    }

    //修改书籍
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
     
     
        System.out.println("updateBook=>"+books);
        int i = bookService.updateBook(books);
        if (i>0){
     
     
            System.out.println("添加Books成功"+books);
        }else {
     
     
            System.out.println("添加Books失败");
        }
        return "redirect:/book/allBook";
    }
}
  • updateBook.jsp modify book page
<%--
  Created by IntelliJ IDEA.
  User: ws199
  Date: 2022/12/3
  Time: 14:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改书籍</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/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>

        <form action="${pageContext.request.contextPath}/book/updateBook" method="post">

            <%--前端隐藏域:页面无法看见,默认提交到后台--%>
            <input type="hidden" name="bookID" value="${books.bookID}">

            <div class="form-group">
                <label>书籍名称:</label>
                <input type="text" name="bookName" class="form-control" value="${books.bookName}" required>
            </div>
            <div class="form-group">
                <label>书籍数量:</label>
                <input type="text" name="bookCounts" class="form-control" value="${books.bookCounts}" required>
            </div>
            <div class="form-group">
                <label>书籍描述:</label>
                <input type="text" name="detail" class="form-control" value="${books.detail}" required>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary">修改</button>
            </div>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>

delete book function

  • BookController.java
package com.wei.controller;

import com.wei.dao.BookMapper;
import com.wei.pojo.Books;
import com.wei.service.BookService;
import org.apache.ibatis.annotations.Param;
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 BookController {
     
     
    //controller 调 service 层
    @Autowired
    @Qualifier("BookServiceImpl")   //指定一个唯一的bean对象注入
    private BookService bookService;

    //查询全部数据,并且返回到一个书籍展示页面
    @RequestMapping("/allBook")
    public String list(Model model) {
     
     
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list", list);
        return "allBook";
    }

    //跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPaper() {
     
     
        return "addBook";
    }

    //添加书籍的请求
    @RequestMapping("/addBook")
    public String addBook(Books books) {
     
     
        System.out.println("addBook:" + books);
        bookService.addBook(books);
        return "redirect:/book/allBook";       //重定向到@RequestMapping("/allBook")请求
    }

    //跳转到修改页面
    @RequestMapping("/toUpdate")
    public String toUpdatePaper(int id, Model model){
     
     
        Books books = bookService.queryBookById(id);
        model.addAttribute("books",books);
        return "updateBook";
    }

    //修改书籍
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
     
     
        System.out.println("updateBook=>"+books);
        int i = bookService.updateBook(books);
        if (i>0){
     
     
            System.out.println("添加Books成功"+books);
        }else {
     
     
            System.out.println("添加Books失败");
        }
        return "redirect:/book/allBook";
    }

    //删除书籍
    @RequestMapping("/deleteBook/{bookID}")
    public String deleteBook(@PathVariable("bookID") int id){
     
     
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }
}

searching feature

  • BookMapper.java
    //查询数据
    Books queryBooksByName(String bookName);
  • BookMapper.xml
<select id="queryBooksByName" parameterType="String" resultType="Books">
    select * from ssmbuild.books where bookName like '%${bookName}%';
</select>
  • BookService.java
//查询数据
Books queryBooksByName(String bookName);
  • BookServiceImpl.java
@Override
public Books queryBooksByName(String bookName) {
     
     
    return bookMapper.queryBooksByName(bookName);
}
  • BookController.java
//查询数据
@RequestMapping("/queryBooks")
public String queryBooks(String queryBookName, Model model) {
     
     
    Books books = bookService.queryBooksByName(queryBookName);
    System.err.println("Books:" + books);
    List<Books> list = new ArrayList<Books>();
    list.add(books);
    System.out.println("queryBookName:" + queryBookName);
    if (books == null || queryBookName == null) {
     
     
        list = bookService.queryAllBook();
        model.addAttribute("Error", "未查到书籍");
    }
    
    model.addAttribute("list", list);
    return "allBook";
}
  • allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: ws199
  Date: 2022/11/28
  Time: 15:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>书籍展示</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/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 class="col-md-8">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">增加书籍</a>
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示全部书籍</a>
        </div>
        <div class="col-md-4">
            <%--查询书籍--%>
            <form action="${pageContext.request.contextPath}/book/queryBooks" method="post">
                <div class="input-group mb-3">
                    <span style="color: red;font-weight: bold;line-height: 32px">${Error}</span>
                    <input type="text" name="queryBookName" class="form-control" placeholder="请输入查询书籍名称" required>
                    <div class="input-group-append">
                        <button class="btn btn-primary" type="submit">查询</button>
                    </div>
                </div>
            </form>
        </div>

    </div>

    <div class="row">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>书籍编号</th>
                    <th>书籍名称</th>
                    <th>书籍数量</th>
                    <th>书籍详细</th>
                    <td>操作</td>
                </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/toUpdate?id=${book.bookID}">修改</a>
                            &nbsp; | &nbsp;
                            <a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_62765017/article/details/128748386