Simple book management system (SSM framework integration + IDEA)

Posted by bokehman on Fri, 04 Mar 2022 15:14:12 +0100

Book management system (SSM framework integration)

preface

The simple book management system implemented with SSM framework can carry out basic CRUD functions.

1, What is the SSM framework?

1.SSM

SSM (Spring + spring MVC + mybatis) framework set is integrated by spring and mybatis (spring MVC is part of spring), which is often used as the framework of web projects with simple data source. SSM framework is a standard MVC mode, which divides the whole system into four layers: DAO layer, Controller layer, Service layer and View layer. Spring MVC is used to forward requests and manage views. Spring realizes business object management, and mybatis is used as the persistence engine of data objects.

2.Mybatis (persistent layer)

DAO layer: the DAO layer mainly does the work of data persistence layer, and some tasks responsible for contacting the database are encapsulated here.

3.Spring (business layer)

Service layer: the service layer is mainly responsible for the logical application design of business modules.
The core idea of Spring is IoC (inversion of control), which means that programmers no longer need to explicitly new an object, but let the Spring framework help you do all this.

4. Spring MVC (presentation layer)

Controller layer: the controller layer is responsible for the control of specific business module processes.
Spring MVC intercepts user requests in the project. Its core Servlet, DispatcherServlet, assumes the responsibilities of intermediary or foreground. It matches user requests to the Controller through HandlerMapping. The Controller is the specific operation corresponding to the request. Spring MVC is equivalent to struts in SSH framework.

5.View (view layer)

The two layers need to be closely combined with View control. The View layer is mainly responsible for the presentation of the foreground jsp page.

2, Use steps

1. Establish Maven project

  • Select new project in the file menu of IDEA, and then find Maven project in the task bar on the left. Set the project name as ssmbuild, fill in the project name, and click finish


2. maven installation

  1. Decompression of compressed package

  2. Configure environment variables
    Right click my computer - > properties - > advanced system settings - > environment variables - > system variable path paste maven's bin path into path
    Local demonstration: [E: \ office \ junior college \ 00 training \ materials \ apache-maven-3.6.3\bin]

    Both maven and jdk environment variables should be configured
    bin: the startup program path, which is also the main configuration directory of environment variables
    Conf: Maven core configuration file

The settings file describes localRepository:
maven local library path. Note that if the warehouse location is consistent with the existing file, the file does not need to be modified. If it is inconsistent, it needs to be modified to the current local library path
mirror: remote warehouse Path

Put m2 local warehouse in the specified path and conf - settings in the downloaded maven folder XML file

<localRepository>m2 Installation path of</localRepository>

3. Control command to test whether Maven can start normally

1. Modify POM XML file

<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/maven-v4_0_0.xsd">
       <!-- Information description of current project-->
   	<modelVersion>4.0.0</modelVersion>
   	<groupId>org</groupId>
   	<artifactId>test</artifactId>
   	<packaging>jar</packaging>
   	<version>0.0.1-SNAPSHOT</version>
       <!-- Used in the current project jar package-->
   	<dependencies>
   	   <dependency>
   		 <groupId>junit</groupId>
   		 <artifactId>junit</artifactId>
   		 <version>4.12</version>
   		 <scope>test</scope>
   	   </dependency>
   	</dependencies>	
   </project>

2. Enter mvn compile in the console. The configuration is correct and maven starts successfully. The error can appear in jdk version, POM XML file, etc.

4.IDEA configuration Maven

(note that Maven in the IDEA needs to be reconfigured every time a new project is created)
1. Initialize and write POM XML file, import dependency.

<?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>com.edu</groupId>
    <artifactId>ssmbuild</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>ssmbuild Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!--Database driven-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- Database connection pool -->
        <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.16.10</version>
        </dependency>
    </dependencies>

    <build>
        <!--Maven Resource filtering settings-->
        <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>


        <finalName>ssmbuild</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

2. After entering the code, import... Will appear in the lower right corner. Click import dependency
3. Click setup - construct, execute, deploy - build tool - Maven
4. Fill in - apply - confirm

5. Maven Runner VM Options in the build tool:

install:install-file -Dfile=D:/ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar -DgeneratePom=true

6. Configure Tomcat server with idea

Click add configurations in the operation box, click Templates - Tomcat Server - Local, click Configure on the far right of Application to enter the Tomcat path selection, Tomcat Home: click the folder on the right to select the folder where the Tomcat is used, and the following Tomcat base directory: automatic identification, OK,

7. Build a web project and configure Tomcat

1. Create a directory called webapp under SRC - > mainpath
2. Manually create WEB-INF under webapp
3. Create a web in the WEB-INF directory xml
Click file - project structure - module - click the plus sign, select Web in the framework, and select webapp \ Web-inf-Web in the path on the right XML, select webapp from the following Web Resource Directory, and create a new index in the webapp directory JSP as the test file, click the project structure - Artifacts, click the plus sign to select Web Application: expanded - From Modules will appear (for example, Maven 2). Click OK to import the war package into the project, apply and confirm.


8. Modify web XML file

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">

    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>DispatcherServlet</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>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--encodingFilter-->
    <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>

9. Click tomcat, edit the configuration, click the plus sign, add Tomcat Local, click the right side to add war package (maven2: War expanded), the following Application context: delete the path, only /, and click application to complete.

10. Test with POM The XML dependency has been imported into the jar package. Run Tomcat 9.0.205, open the default browser, and the index The content of the JSP page indicates that the test is successful and you can start the next step.

3, Establish basic structure and configuration framework

1.MyBatis layer

1. Create four folders

controller (core control layer)
dao (data persistence layer)
pojo (view layer)
service (business logic layer)

2. Prepare configuration file

The SSM framework is Spring + spring MVC + mybatis. The three configuration files are written separately. Because they are the configuration files of the project, except web XML, and other configuration file suggestions about the whole project are put in resource.
mybatis 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>
    <!--Configure the data source and give it to spring Do it-->
    <typeAliases>
        <package name="com.yang.pojo"/>
    </typeAliases>
    <mappers>
        <mapper resource="com/yang/dao/BookMapper.xml"/>
    </mappers>
</configuration>

Spring configuration file
Create a new configuration file ApplicationContext XML, paving the way for the integration of interactive configuration files at all levels below.
Next, three spring configuration files will be created as the interaction between the front and back end and the entity class.

<?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="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="spring-mvc.xml"/>
</beans>


Associated database file

jdbc.driver=com.mysql.jdbc.Driver
#Mysql8.0 or above, add a time zone configuration, URL & servertimezone = Asia / Shanghai

jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456


Connect database

After entering the account and password, test whether the connection is successful

The effect picture of successful connection. The database name of this project is mybatis and the table name is books

2. Write entity class

Books

package com.yang.pojo;
//@Data / / there are all kinds of structures except parameter structures
//@AllArgsConstructor / / the structure with parameters is added, but the structure without parameters is lost
//@NoArgsConstructor / / add no parameter
public class Books {

    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
    @Override
    public String toString() {
        return "Books{" +
                "bookID=" + bookID +
                ", bookName='" + bookName + '\'' +
                ", bookCounts=" + bookCounts +
                ", detail='" + detail + '\'' +
                '}';
    }
    public Books() {
    }

    public Books(int bookID, String bookName, int bookCounts, String detail) {
        this.bookID = bookID;
        this.bookName = bookName;
        this.bookCounts = bookCounts;
        this.detail = detail;
    }
    public int getBookID() {
        return bookID;
    }

    public void setBookID(int bookID) {
        this.bookID = bookID;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public int getBookCounts() {
        return bookCounts;
    }

    public void setBookCounts(int bookCounts) {
        this.bookCounts = bookCounts;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }
}

3. Write the corresponding data layer

BookMapper

package com.yang.dao;
import org.apache.ibatis.annotations.Param;
import com.yang.pojo.Books;
import java.util.List;
public interface BookMapper {

    //Add a Book
    int addBook(Books book);

    //Delete a Book by id
    int deleteBookById(@Param("bookId") int id);

    //Update Book
    int updateBook(Books books);

    //According to the id query, a Book is returned
    Books queryBookById(@Param("bookId") int id);

    //Query all books and return the list set
    List<Books> queryAllBook();
}

BookMapper profile

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.yang.dao.BookMapper">

    <!--Add one Book-->
    <insert id="addBook" parameterType="Books">
        insert into mybatis.books(bookName,bookCounts,detail)
        values (#{bookName}, #{bookCounts}, #{detail})
    </insert>

    <!--according to id Delete a Book-->
    <delete id="deleteBookById" parameterType="int">
        delete from mybatis.books where bookID=#{bookId}
    </delete>

    <!--to update Book-->
    <update id="updateBook" parameterType="Books">
        update mybatis.books
        set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
        where bookID = #{bookID}
    </update>

    <!--according to id query,Return a Book-->
    <select id="queryBookById" resultType="Books">
        select * from mybatis.books
        where bookID = #{bookId}
    </select>

    <!--Query all Book-->
    <select id="queryAllBook" resultType="Books">
        SELECT * from mybatis.books
    </select>

</mapper>

BookService

package com.yang.service;
import com.yang.pojo.Books;
import java.util.List;

//BookService: it needs to be implemented at the bottom and call the dao layer
public interface BookService {
    //Add a Book
    int addBook(Books book);
    //Delete a Book by id
    int deleteBookById(int id);
    //Update Book
    int updateBook(Books books);
    //According to the id query, a Book is returned
    Books queryBookById(int id);
    //Query all books and return the list set
    List<Books> queryAllBook();
}

BookServiceImpl

package com.yang.service;
import org.springframework.stereotype.Service;
import com.yang.dao.BookMapper;
import com.yang.pojo.Books;

import java.util.List;
@Service
public class BookServiceImpl implements BookService {
    //service layer to dao layer
    //Call the operation of dao layer and set a set interface to facilitate Spring management
    private BookMapper bookMapper;

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

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

    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();
    }
}

2.Spring layer and spring MVC layer

Configure spring MVC, configure jsp to display ViewResolver, view parser, and scan web related bean s.

1. Prepare configuration file

spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Configuration integration mybatis -->
    <!-- 1.Associated database file -->
    <context:property-placeholder location="classpath:database.properties"/>

    <!-- 2.Database connection pool -->
    <!--Database connection pool
     dbcp  Semi automatic operation cannot be connected automatically
     c3p0  Automatic operation (automatically load the configuration file and set it into the object)
     druid Druids are Java The best database connection pool in the language. Druid It can provide powerful monitoring and expansion functions.
    -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- Configure connection pool properties -->
        <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 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 10 s-->
        <property name="checkoutTimeout" value="10000"/>
        <!-- Number of retries when getting connection failed -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

    <!-- 3.to configure SqlSessionFactory object -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- Inject database connection pool -->
        <property name="dataSource" ref="dataSource"/>
        <!-- to configure MyBaties Global profile:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- 4.Configure scan Dao Interface package, dynamic implementation Dao Interface injection into spring In container -->
    <!--Explanation: https://www.cnblogs.com/jpfss/p/7799806.html-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- injection sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- Given the need to scan Dao Interface package -->
        <property name="basePackage" value="com.yang.dao"/>
    </bean>

</beans>

Next, we need to write Spring MVC and Spring Service. These two configuration files are the configuration files of Spring integrating Spring MVC. We know that the ssm framework relies on Spring MVC to realize the front-end and back-end interaction, so the call between layers is also the Controller (control layer) calling Service (business layer), Service (business layer) calling Dao (persistence layer), So scan the spring-mvc.net of the Controller layer The XML code is as follows.

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- to configure SpringMVC -->
    <!-- 1.open SpringMVC Annotation driven -->
    <mvc:annotation-driven />
    <!-- 2.Static resource default servlet to configure-->
    <mvc:default-servlet-handler/>
    <!-- 3.to configure jsp display ViewResolver view resolver  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 4.scanning web dependent bean -->
    <context:component-scan base-package="com.yang.controller" />

</beans>

spring-service.xml
Spring Service is the configuration scanning 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
    http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- scanning service dependent bean -->
    <context:component-scan base-package="com.yang.service" />

    <!--BookServiceImpl Inject into IOC In container-->
    <bean id="BookServiceImpl" class="com.yang.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <!-- Configure transaction manager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- Inject database connection pool -->
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

Click the Project Structure described above and then click Module. We can see the logical and clear relationship structure of all configuration files

3. Write code

1.controller layer

The controller layer can be regarded as the core of the whole program. Our business logic is written here. In fact, this layer is well understood. Now we have a back-end database. The controller layer is a channel for front-end and back-end interaction, and the code of this layer is relatively regular. First, we create a BookController class to realize CRUD and other functions and pass it to the front-end page. The code is as follows:

package com.yang.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.yang.pojo.Books;
import com.yang.service.BookService;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    @Qualifier("BookServiceImpl")
    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 addPaper(Books books) {
        System.out.println(books);
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }

    @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";
    }
    @RequestMapping("/del/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id) {
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }
}

4. Front end interface

web.xml is actually to write a response request and a filter.

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">

    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <servlet-name>DispatcherServlet</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>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--encodingFilter-->
    <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>

1. Home page

Create an index JSP file to make a home page for our book management system

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
    <title>home page</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">Click to enter the list page</a>
</h3>
</body>
</html>

2. Query page

Suggest an allbook JSP file.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>List of 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>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">newly added</a>
        </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>
                <tbody>
                <c:forEach var="book" items="${requestScope.get('list')}">
                    <tr>
                        <td>${book.getBookID()}</td>
                        <td>${book.getBookName()}</td>
                        <td>${book.getBookCounts()}</td>
                        <td>${book.getDetail()}</td>
                        <td>
                            <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">change</a> |
                            <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">delete</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

3. New page

Suggest an addlbook JSP file.

<%@ 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">
        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"><br><br><br>
        <input type="submit" value="add to">
    </form>

</div>

</body>
</html>

4. Modify and delete interface

Suggest an updatebook JSP file.

<%@ 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">
        <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, Operation effect diagram display

Query rendering

New renderings

Modify renderings


Delete renderings

5, Troubleshooting ideas

1. Null pointer problem

Problem: bean does not exist
1. Check whether bean injection is successful, spring service XML file √

2. Does JUnit test unit test query?
Add a test java√

3. There is no problem in the first two steps. The problem is not at the bottom. It is spring that has a problem. Spring MVC may have a problem.

4. Spring MVC, bean s that are not called to our service layer during integration:

  • applicationContext.xml does not inject bean s
  • web. The configuration file has also been bound in XML. If problems are found, we configure spring MVC There is no service bean in the XML file, so a null pointer is reported.


Correct the error and operate normally

2.Mapper.xml
The most easily overturned part of this configuration file is the sql statement. When deleting and modifying modules together, you can consider deleting modules and troubleshooting them together.

3.web.xml
You are configuring web When using XML, you should pay attention to the path problem and directly scan ApplicationContext XML is enough, because this configuration file includes the other three configuration files

4. Common problems of classes and interfaces
When you write code, you must correspond to the object name and pay attention to spelling.

summary

This is a complete process of integration of simple book management. This project is just a simple CRUD operation for books, which is easy for novices to start. The focus is on the integration idea and implementation principle of the three frameworks, front and back-end interaction. Pay more attention to understanding the idea of the framework, and don't copy the code without understanding the core idea.

Topics: Java Spring SSM