Stay up late at Christmas to sort out a set of SSM templates, so that you can quickly build an environment

Posted by tambo on Wed, 05 Jan 2022 09:29:10 +0100

🏇 Small wood come Yes \textcolor{Orange} {here comes Koki} Here comes Koki
🍣 no have too many of word language , but yes win as if have word , \textcolor{green} {there are not many words, but it is better than words,} There are not many words, but it is better than words, Hope at stay b l i n k hair surface of can with become really \textcolor{red} {I hope what published in blink can come true} I hope the published in blink can come true 🍣
🍣 this in only carry Supply one individual S S M model plate . \textcolor{green} {only one SSM template is provided here.} Only one SSM template is provided here. Give Way you no again by Yes ring Boundary hair Worry , more large of essence power stay trade Affairs Logic Compilation upper \textcolor{red} {allows you to stop worrying about the environment and focus more on business logic} Let you no longer worry about the environment and focus more on business logic 🍣
🙏 Bo main also stay learn Learn rank paragraph , as if hair present ask topic , please Tell know , wrong often sense thank \textcolor{Orange} {blogger is also in the learning stage. If you find any problems, please let me know. Thank you very much} Bloggers are also in the learning stage. If you find any problems, please let us know. Thank you very much 💗
Welcome to my friends 😄 follow 👍 give the thumbs-up ⭐ Collection 📝 Leaving a message.

If you want a template, you can get it from the resource, or leave a comment and I'll send it to you 🤭

1, Environment construction

  • IDEA
  • MySQL 8.0.26
  • Tomcat 9.0.31
  • Maven 3.8.2

1. Database

CREATE DATABASE `wmmbooks`;

USE `wmmbooks`;

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT 'book id',
`bookName` VARCHAR(100) NOT NULL COMMENT 'title',
`bookCounts` INT(11) NOT NULL COMMENT 'quantity',
`detail` VARCHAR(200) NOT NULL COMMENT 'describe',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT  INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'From getting started to giving up'),
(2,'MySQL',10,'From deleting the library to running away'),
(3,'Linux',5,'From entering the door to entering the prison');

2. Basic environment construction

2.1 create an ordinary maven project, wmmbooks,

2.2 import related dependencies

maven warehouse

<!--Dependency: junit,Database driver, connection pool, servlet,jsp,mybatis,mybatis-spring,spring-->
<dependencies>
    <!--Junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <!--Database driven-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version>
    </dependency>
    <!-- Database connection pool: c3p0 Used before dbcp-->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.5</version>
    </dependency>

    <!--Servlet - JSP -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.3</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp.jstl</groupId>
        <artifactId>jstl-api</artifactId>
        <version>1.2</version>
    </dependency>

    <!--Mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>

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

<!--Static resource export problem-->
<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>

2.3 connecting to database

2.4 establish basic architecture and configuration framework

  • com.hxl.dao

  • com.hxl.pojo

  • com.hxl.service

  • com.hxl.controller

  • com.hxl.utils

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

2, Mybatis layer

1. Connect to database

1.1 create database properties

I use mysql8 0. If the connection fails, you need to add a time zone configuration & servertimezone = Asia / Tianjin

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/wmmbooks?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&allowPublicKeyRetrieval=true
user=root
password=123456

2. Create entity class

package com.hxl.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;
}

Remember to import the lombok package

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.20</version>
</dependency>

3. Interface

package com.hxl.dao;

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

import java.util.List;

public interface BookMapper {

    //increase
    int addBook(Books books);
    //delete
    int deleteBookById(@Param("bookId")int id);
    //to update
    int updateBook(Books books);
    //Inquire about a Book
    Books queryBookById(int id);
    //Check all the books
    List<Books> queryAllBook();
}

BookMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hxl.dao.BookMapper">
    <insert id="addBook" parameterType="Books">
        insert into wmmbooks.books (bookName,bookCounts,detail)
         values (#{bookName},#{bookCounts},#{detail})
    </insert>

    <!--Write here int yes Integer,write_int actually is int. however java It can be converted, unpacked and boxed automatically-->
    <!--Write here bookId Because it is used in the interface@Param This annotation, otherwise it needs to be written id-->
    <delete id="deleteBookById" parameterType="int">
        delete from wmmbooks.books where bookID = #{bookId}
    </delete>

    <update id="updateBook" parameterType="Books">
        update wmmbooks.books
        set bookName = #{bookName}, bookCounts=#{bookCounts},detail=#{detail}
        where bookID = #{bookID}
    </update>

    <select id="queryBookById" parameterType="Books">
        select * from wmmbooks.books where bookID = #{bookID}
    </select>

    <select id="queryAllBook" parameterType="Books">
        select * from wmmbooks.books
    </select>
</mapper>

After writing, you need to bind it to the mybatis configuration file immediately

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

4. Business layer

BookService

package com.hxl.service;

import com.hxl.pojo.Books;

import java.util.List;

public interface BookService {
    //increase
    int addBook(Books books);
    //delete
    int deleteBookById(int id);
    //to update
    int updateBook(Books books);
    //Inquire about a Book
    Books queryBookById(int id);
    //Check all the books
    List<Books> queryAllBook();
}

After writing, write its implementation class BookServiceImpl

package com.hxl.service;

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

import java.util.List;

public class BookServiceImpl implements BookService{
    //service layer adjustment, combination Dao
    private BookMapper bookMapper;
    //Give it a set method so that spring can host it
    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> queryAllBook() {
        return bookMapper.queryAllBook();
    }
}

3, Spring layer

1.spring-dao.xml

Spring integrates relevant configuration files of Mybatis; Integrate 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">
    <!--1.Associated database profile-->
    <context:property-placeholder location="classpath:database.properties"/>
    <!--2.Connection pool
        dbcp:Semi automatic operation, unable to connect automatically
        c3p0:Automatic operation, which can automatically load the configuration file and automatically set it to the object
        druid:
        hikari: 
    -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${driver}"/>
        <property name="jdbcUrl" value="${url}"/>
        <property name="user" value="${user}"/>
        <property name="password" value="${password}"/>

        <!-- c3p0 Private properties of connection pool -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- Not automatically after closing the connection commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- Get connection timeout -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- Number of retries when getting connection failed -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

    <!--3.sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--binding Mybatis Configuration file for-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!--4.to configure dao The interface scanning package is dynamically implemented Dao Interface can be injected into Spring In container-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--injection sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--To scan dao package-->
        <property name="basePackage" value="com.hxl.dao"/>
    </bean>
</beans>
  • Connection pool
    • dbcp: semi automatic operation, unable to connect automatically
    • c3p0: automatic operation, which can automatically load the configuration file and automatically set it to the object
    • druid: hikari:

Scan the above Factory and dynamically scan it into beanName

2.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">

    <!--1.scanning service Package under-->
    <context:component-scan base-package="com.hxl.service"/>

    <!--2.Inject all our business classes into SpringIOC In the container, it can be implemented by configuration or annotation-->
    <bean id="BookServiceImpl" class="com.hxl.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <!--3.Declarative transaction configuration-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--Injection data source-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--4.aop Transaction support-->
</beans>

To use AOP transaction support, you need to import an AOP weaving package aspectjweaver

3. Solve the problem that the configuration files are not together

Here we should ensure that they are together, otherwise they cannot be integrated;

The local report red in the circle proves that it is not integrated.

There are two ways to solve the red explosion

1. Make them in the same context through idea, and make them all in the same application in module

2. import

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

3. Can be added in applicationContext

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

4. Inject business classes into Spring

You can configure spring service xml

<bean id="BookServiceImpl" class="com.hxl.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

Annotation implementation

4, Spring MVC

1. Add web support

2.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--DispatchServlet-->
    <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:spring-mvc.xml</param-value>
        </init-param>
        <!--and tomcat One piece start-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--Random code filtering-->
    <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 Expiration time-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

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

    <!--1.Annotation driven-->
    <mvc:annotation-driven/>
    <!--2.Static resource filtering-->
    <mvc:default-servlet-handler/>
    <!--3.Scan package: controller-->
    <context:component-scan base-package="com.hxl.controller"/>
    <!--4.view resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

At this point, we need to complete the framework

4. Spring integration 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">

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

5. File declaration in XML

It is possible that the error generated automatically needs to be modified to change the cache to mvc

5, Configure tomcat

No more details, start the test

At this point, the SSM framework is integrated. At this time, we can save this part and apply it in future projects.

6, Problems encountered

1. The project cannot be deployed

Artifact wmmbooks:war exploded: Error during artifact deployment. See server

terms of settlement:

Right click to import the jar package

2. Database connection error c3p0

Check database db properties

  • java.sql.SQLNonTransientConnectionException: Public Key Retrieval is not allowed

    • Just add allowPublicKeyRetrieval=true after the url
  • java.sql.SQLException: Access denied for user 'Administrator'@'localhost'

    • There may be a conflict between username and the system. Modify it to user.
  • The database connection after 8.0 should be added cj, no need to add 5.0

    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/wmmbooks?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&allowPublicKeyRetrieval=true
    
  • It may also be useSSL=true. Just change it to false.

  • serverTimezone=UTC, time zone, some GMT

  • ORG.MYBATIS.SPRING.MYBATISSYSTEMEXCEPTION: NESTED EXCEPTION IS ORG.APACHE.IBATIS.EXCEPTIONS

    • The problem is that your database operation is wrong. Maybe the parameter type and result type are written incorrectly

3. Configuration file

It says that if the bookService is not found, we can proceed step by step according to the following ideas

Troubleshooting ideas (important)

The problem is: the bean does not exist

Steps:

  1. Check whether the bean injection is successful

  2. Junit unit test to see if the code can query the results

  3. The problem is not at the bottom, that is, there is a problem with spring

  4. Spring MVC did not call our service layer bean s during integration;

    • There are no injected bean s in applicationContextxml

    • web. We also bound the configuration file in XML and found the problem. We configured spring MVC XML, there is really no service bean here, so an error is reported

At this point, the problem is found and you can jump. The rest is optimization.

7, Query all books

1.BookController

package com.hxl.controller;

import com.hxl.pojo.Books;
import com.hxl.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 {
    //The controller calls the service layer
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //Query all the books and return to a book display page
    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list", list);
        return "allBook";
    }
}

2. Compile the home page index jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/11/8
  Time: 16:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <style type="text/css">
      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">Enter the book display page</a>
  </h3>
  </body>
</html>

3. Book list allbook jsp

<!--c Label introduction,Remember to introduce jstl of jar Bao He standard of jar package-->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Book display</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- introduce Bootstrap cdn-->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<h1>Book display</h1>
</body>
<div class="container">
    <%--Clear float--%>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>Book list - displays all books</small>
                </h1>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">New books</a>
        </div>
        <div class="col-md-4 column">
           <%--Query books--%>
            <form action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float:right" class="form-inline">
                <input type="text" name="queryBookName" class="form-control" placeholder="Please enter the name of the book to query">
                <input type="submit" value="query" class="btn btn-primary">
            </form>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>Book number</th>
                    <th>Book name</th>
                    <th>Number of books</th>
                    <th>Book details</th>
                    <th>operation</th>
                </tr>
                </thead>
                <%--Books are queried from the database list From the data,--%>
                <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?id=${book.getBookID()}">change</a> |
                            <a href="${pageContext.request.contextPath}/book/delete/${book.getBookID()}">delete</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</html>

Note here that to introduce tags, you need to add a standard dependency

<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

8, Add books

1.allBook.jsp

2.BookController

//Jump to add book page
@RequestMapping("/toAddBook")
public String toAddPaper(){
    return "addBook";
}

3. Add addbook jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>New books</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- introduce 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>New books</small>
                </h1>
            </div>
        </div>
    </div>
    <form action="${pageContext.request.contextPath}/book/addBook" method="post">
        <%--The properties here should be consistent with those in the entity class--%>
        Book Name:<input type="text" name="bookName"><br><br><br>
        Number of books:<input type="text" name="bookCounts"><br><br><br>
        Book details:<input type="text" name="detail" required><br><br><br>
        <input type="submit" value="add to">
    </form>

</div>
</body>
</html>

4.BookController

@RequestMapping("/addBook")
public String addPaper(Books books) {
    System.out.println(books);
    bookService.addBook(books);
    //Redirect to our allBook request
    return "redirect:/book/allBook";
}

Click the button at the front end to jump. In the control layer, let it jump to the add page, enter relevant information in the page, and click submit to operate in the control layer. End redirection back to allBook request

Add required here. In this way, if no content is entered on the page, you will be prompted to enter the content

9, Modify delete books

1. Realize page reuse in allBook

2.BookController

@RequestMapping("/toUpdateBook")
public String toUpdateBook(Model model, int id) {
    Books books = bookService.queryBookById(id);
    System.out.println(books);
    model.addAttribute("book",books );
    return "updateBook";
}

@RequestMapping("/updateBook")
public String updateBook(Model model, Books book) {
    System.out.println(book);
    bookService.updateBook(book);
    Books books = bookService.queryBookById(book.getBookID());
    model.addAttribute("books", books);
    return "redirect:/book/allBook";
}

3. Modify page updateBook

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Modify information</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- introduce 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>Modify information</small>
                </h1>
            </div>
        </div>
    </div>

    <form action="${pageContext.request.contextPath}/book/updateBook" method="post">
        <%--Without any problems, the revised version was submitted sql The request, but the modification failed. The transaction was considered for the first time. After configuring the transaction, it still failed--%>
        <%--to glance at sql Statement, whether it can be executed successfully, sql Execution failed, modification not completed--%>
        <%--Forward pass hidden field--%>
        <%--id Pass it, or it won't succeed.--%>
        <input type="hidden" name="bookID" value="${book.getBookID()}"/>
        Book Name:<input type="text" name="bookName" value="${book.getBookName()}"/>
        Number of books:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/>
        Book details:<input type="text" name="detail" value="${book.getDetail() }"/>
        <input type="submit" value="Submit"/>
    </form>

</div>
</body>
</html>

4. Delete books

@RequestMapping("/del/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
    bookService.deleteBookById(id);
    return "redirect:/book/allBook";
}

As long as you add a jar package, you need to package it. Go to lib in artifact

Add log function

Added in mybatis config

<settings>
    <!--Standard log factory implementation-->
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

10, Query box

1. Add query function to allbook

<div class="col-md-4 column">
    <%--Query books--%>
    <form action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float:right">
        <input type="text" name="queryBookName" class="form-control" placeholder="Please enter the name of the book to query">
        <input type="submit" value="query" class="btn btn-primary">
    </form>
</div>

We design from top to bottom and develop from bottom to top.

2. Dao - > bookmapper, and xml

//Inquiry Book
Books queryBookByName(@Param("bookName") String bookName);
<select id="queryBookByName" resultType="Books">
    select * from books where bookName = #{bookName}
</select>

3. Service - > bookservice and Impl

//Inquiry Book
Books queryBookByName(String bookName);
public Books queryBookByName(String bookName) {
    return bookMapper.queryBookByName(bookName);
}

So far, the bottom is done

4.BookController

//Query books
@RequestMapping("/queryBook")
public String Book(String queryBookName, Model model){
    Books books = bookService.queryBookByName(queryBookName);
    List<Books> list = new ArrayList<Books>();
    list.add(books);
    model.addAttribute("list", list);
    return "allBook";
}

Now we can run.

Our front end can use tags to receive information transmitted from the back end, such as

<span>${error}</span>
model.addAttribute("error","Not found");

Java learning route summary, brick movers counter attack Java Architects

Finally, I wish her success in the postgraduate entrance examination 🤭

Topics: Java Maven SSM intellij-idea