[SSM] Spring + Spring MVC + Mybatis integration

1. Environmental construction

1.1 database files

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int NOT NULL AUTO_INCREMENT COMMENT 'id Primary key',
  `username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'user name',
  `password` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'User password',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'admin', 'admin');
INSERT INTO `user` VALUES (2, 'tom', 'tom');
INSERT INTO `user` VALUES (3, 'kate', 'kate');

SET FOREIGN_KEY_CHECKS = 1;

1.2 create Maven project

[1] Click: File - > module, select Maven, check Create from achetype, select webapp, as shown in the figure below, and click NEXT

[2] Create a module name, name the project and save it to the corresponding path, and click NEXT

[3] Select maven configuration (it can be left unchecked), and click Finish

[4] The directory structure is as follows:

1.3 introducing dependencies

<?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.spg</groupId>
  <artifactId>ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssm 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.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>5.0.2.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>8.0.16</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>
    <!-- spring -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>


    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- log end -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>ssm</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>

1.3 create java and resources folders

Create java and resources folders under the main directory and set the corresponding files

1.4 create class and interface files

Create class files in the java folder. The required class files are as follows:

[1] The user class under the domain package of JavaBean: com.spg.domain.User

package com.spg.domain;

/**
 * User class
 * @author shangpange
 */
public class User {
    private Integer id;
    private String username;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

[2] User Dao interface under Dao package of data access layer: com.spg.dao.UserDao

package com.spg.dao;

import com.spg.domain.User;

import java.util.List;

/**
 * User persistence layer interface
 * @author shangpange
 */
public interface UserDao {

    // Query all users
    public List<User> findAllUser();
    
    // User registration
    public Integer insertUser(User user);

    // User login
    public User login(User user);
}

[3] UserService interface under service package of business layer: com.spg.service.UserService

package com.spg.service;

import com.spg.domain.User;

import java.util.List;

/**
 * User business logic layer
 * @author shangpange
 */
public interface UserService {

    // Query all users
    public List<User> findAllUser();

    // User registration
    public Integer insertUser(User user);

    // User login
    public User login(User user);

}

[4] The service implementation class under the service package of the business layer inherits the service interface: com.spg.service.impl.UserServiceImpl

package com.spg.service.impl;

import com.spg.domain.User;
import com.spg.service.UserService;

import java.util.List;

/**
 * User business logic implementation class
 * @author shangpange
 */
public class UserServiceImpl implements UserService {

    @Override
    public List<User> findAllUser() {
        System.out.println("Business layer: query users");
        return null;
    }

    @Override
    public Integer insertUser(User user) {
        System.out.println("Business layer: user registration");
        return null;
    }

    @Override
    public User login(User user) {
        System.out.println("Business layer: user login");
        return null;
    }
}

[5] User control layer UserController class under control layer controller package: com.spg.controller.UserController

package com.spg.controller;

/**
 * User controller
 * @author shangpange
 */
public class UserController {

}

1.5 create profile

Create multiple configuration files under the resources folder, mainly including:

[1] Spring related configuration: spring.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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	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/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx.xsd">
	
</beans>

[2] Spring MVC related configuration: spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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 
       http://www.springframework.org/schema/mvc 
       http://www.springframework.org/schema/mvc/spring-mvc.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd">
 
</beans>

[3] Mybatis related configuration: mybatis.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>

[4] Log related configuration: log4j.properties

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE
 
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
 
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
 
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

[5] The directory structure is as follows:

2. Write Spring framework

2.1 configuring annotation scanning

Configure annotation scanning in spring.xml and add the following configuration:

<!--Enable annotation scanning, here service and dao It needs to be scanned, controller There is no need to scan-->
<context:component-scan base-package="com.spg">
    <!--Configure annotations to ignore-->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

2.2 add annotation for service implementation class

Add an annotation in the UserServiceImpl class and hand over the service to the IOC container for management

@Service("userService")
public class UserServiceImpl implements UserService {

    @Override
    public List<User> findAllUser() {
        System.out.println("Business layer: query users");
        return null;
    }
}

2.3 testing spring framework

Here, we only do user query test and create a test class: com.spg.test.SpringTest

package com.spg.test;

import com.spg.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Spring Test class
 * @author shangpange
 */
public class SpringTest {

    @Test
    public void TestFindAllUser(){
        // Load profile
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml");
        // Get object
        UserService userService = (UserService) ac.getBean("userService");
        // Call method
        userService.findAllUser();
    }

}

After running and printing the following information, the setup is successful:

3. Write Spring MVC framework

3.1 configuring web.xml

  • Configure front-end controller
  • Load the spring-mvc.xml configuration file
  • Start the server and create a Servlet
  • Configure filter to solve Chinese garbled code
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
 <display-name>Archetype Created Web Application</display-name>

 <!--Filter for solving Chinese garbled code-->
 <filter>
   <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
   <url-pattern>/*</url-pattern>
 </filter-mapping>

 <!--Configure front-end controller-->
 <servlet>
   <servlet-name>dispatcherServlet</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <!--load spring-mvc.xml configuration file-->
   <init-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:spring-mvc.xml</param-value>
   </init-param>
   <!--Start the server and create the servlet-->
   <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
   <servlet-name>dispatcherServlet</servlet-name>
   <url-pattern>/</url-pattern>
 </servlet-mapping>
 
</web-app>

3.2 configuring spring-mvc.xml

  • Enable annotation scanning and only scan controller
  • Configure view parser
  • Filter static resources
  • Enable spring MVC annotation support
<!--Enable annotation scanning, only scanning Controller annotation-->
<context:component-scan base-package="com.spg">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
 
<!--Configured view parser object-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"/>
    <property name="suffix" value=".jsp"/>
</bean>
 
<!--Filter static resources-->
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/js/" mapping="/js/**" />
 
<!--open SpringMVC Annotation support-->
<mvc:annotation-driven/>

3.3 testing spring MVC

[1] Write UserController user control layer

package com.spg.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * User controller
 * @author shangpange
 */

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/findAllUser")
    public String findAllUser() {
        System.out.println("Presentation layer: query users");
        return "user";
    }
}

[2] Write the index.jsp page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>SSM</title>
</head>
<body>
    <a href="/user/findAllUser">Query user</a>
</body>
</html>

[3] Write jump page
Create a new pages directory under the WEB-INF directory, create a user.jsp page under the pages directory, and write user.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>SSM</title>
</head>
<body>
    <h3>Query all users!</h3>
</body>
</html>

[4] Deploy the Tomcat project and test it

Test results:

4. Spring integrates Spring MVC framework

Using the spring framework to integrate the Spring MVC framework is to use the controller layer method to call the service business layer method. How to implement it? The analysis is as follows:

  1. The browser sends a request and loads the springmvc.xml configuration file through the front-end controller configured in web.xml.
  2. Configure the Spring listener in the springmvc.xml configuration file. By default, only the spring.xml configuration in the WEB-INF directory is loaded
    Set file.
  3. Inject the service into the controller and call the method of the service object to test.

4.1 configuring web.xml

Configure the listener and file path for Spring

<!--to configure Spring The default listener is only loaded WEB-INF Under directory spring.xml configuration file-->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--Set the path of the configuration file-->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring.xml</param-value>
</context-param>

4.2 service injection controller

Modify the UserController class, inject the service into the controller, and call the method of the service object to test. After modification, it is as follows:

package com.spg.controller;

import com.spg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * User controller
 * @author shangpange
 */

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/findAllUser")
    public String findAllUser() {
        System.out.println("Presentation layer: query users");
        // Call the method of the service object
        userService.findAllUser();
        return "user";
    }
}

4.3 test run

After clicking the test query link, print the information in the background to show that spring has successfully integrated Spring MVC

5. Prepare MyBatis framework

5.1 configuring the mybatis.xml configuration file

Add the following configuration in the configuration tab:

<!-- Configuration environment -->
<environments default="mysql">
    <environment id="mysql">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"/>
            <property name="username" value="root"/>
            <property name="password" value="root"/>
        </dataSource>
    </environment>
</environments>
<!-- Import mapping profile -->
<mappers>
    <package name="com.spg.dao"/>
</mappers>

5.2 writing UserDao class

package com.spg.dao;

import com.spg.domain.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * User persistence layer interface
 * @author shangpange
 */
public interface UserDao {

    // Query all users
    @Select("select * from user")
    public List<User> findAllUser();

    // User registration
    @Insert("insert into user (username, password) values (#{username}, #{password})")
    public Integer insertUser(User user);

    // User login
    @Select("select * from user where username = #{username} and password = #{password}")
    public User login(User user);
}

5.3 writing test classes

Here you can test user query and registration, and create a test class: com.spg.test.MyBatisTest

package com.spg.test;

import com.spg.dao.UserDao;
import com.spg.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * MyBatis Test class
 * @author shangpange
 */
public class MyBatisTest {

    /**
     * Test query
     * @throws IOException
     */
    @Test
    public void TestFindAllUser() throws IOException {
        // 1. Load configuration file
        InputStream in = Resources.getResourceAsStream("mybatis.xml");
        // 2. Create SqlSessionFactory object
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 3. Create SqlSession object
        SqlSession session = factory.openSession();
        // 4. Get proxy object
        UserDao userDao = session.getMapper(UserDao.class);
        // 5. Query data
        List<User> userList = userDao.findAllUser();
        for (User user : userList) {
            System.out.println(user);
        }
        // 6. Close resources
        session.close();
        in.close();
    }

    /**
     * Test add
     * @throws IOException
     */
    @Test
    public void TestInsertUser() throws IOException {
        User user = new User();
        user.setUsername("jerry");
        user.setPassword("jerry");
        // 1. Load configuration file
        InputStream in = Resources.getResourceAsStream("mybatis.xml");
        // 2. Create SqlSessionFactory object
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 3. Create SqlSession object
        SqlSession session = factory.openSession();
        // 4. Get proxy object
        UserDao userDao = session.getMapper(UserDao.class);
        // 5. Query data
        Integer count = userDao.insertUser(user);
        if(count > 0){
            System.out.println("Successfully added!");
        } else {
            System.out.println("Failed to add!");
        }
        // 6. Submission of services
        session.commit();
        // 7. Close resources
        session.close();
        in.close();

    }
}

Test query users and test registered users can query user data and register successfully, which indicates that the mybatis framework is built successfully.

6. Spring integrates MyBatis framework

If Spring wants to successfully integrate the Mybatis framework, it needs the service layer to successfully call the dao object, and then add, delete, modify and query the relevant database.

  • Save the dao proxy object to the IOC container
  • Inject dao through service

6.1 configuring spring.xml

  • Configure connection pool
  • Configure SqlSessionFactory factory
  • Configure the package of UserDao interface
<!--Spring integration MyBatis frame-->
<!--Configure connection pool-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC"/>
    <property name="user" value="root"/>
    <property name="password" value="root"/>
</bean>

<!--to configure SqlSessionFactory factory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
</bean>

<!--to configure UsersDao Interface package-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.spg.dao"/>
</bean>

After the configuration is completed, there is nothing to do with mybatis.xml, which can be deleted

6.2 injecting dao data

Modify Userdao class and add annotation

@Repository
public interface UserDao {

6.3 inject dao into service

Modify UserServiceImpl class as follows:

package com.spg.service.impl;

import com.spg.dao.UserDao;
import com.spg.domain.User;
import com.spg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * User business logic implementation class
 * @author shangpange
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<User> findAllUser() {
        System.out.println("Business layer: query users");
        return userDao.findAllUser();
    }

    @Override
    public Integer insertUser(User user) {
        System.out.println("Business layer: user registration");
        return userDao.insertUser(user);
    }

    @Override
    public boolean login(User user) {
        System.out.println("Business layer: user login");
        if (userDao.login(user) != null){
            return true;
        } else {
            return false;
        }
    }
}

6.4 test user query, registration and login

[1] Modify the UserController class and display the data on the page as follows:

package com.spg.controller;

import com.spg.domain.User;
import com.spg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * User controller
 * @author shangpange
 */

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * Query user
     * @param model
     * @return
     */
    @RequestMapping("/findAllUser")
    public String findAllUser(Model model) {
        System.out.println("Presentation layer: query users");
        // Call the method of the service object
        List<User> userList = userService.findAllUser();
        model.addAttribute("userList", userList);
        return "user";
    }

    /**
     * User registration
     * @param user
     * @return
     */
    @RequestMapping("/insertUser")
    public String insert(User user){
        System.out.println("Presentation layer: user registration");
        // Call the method of the service object
        Integer count = userService.insertUser(user);
        if(count > 0){
            return "regist_success";
        } else {
            return "regist_failed";
        }
    }

    /**
     * User login
     * @param user
     * @return
     */
    @RequestMapping("/login")
    public String login(User user){
        System.out.println("Presentation layer: user login");
        // Call the method of the service object
        boolean isLogin = userService.login(user);
        if(isLogin){
            return "login_success";
        } else {
            return "login_failed";
        }
    }
}

[2] Modify the index.jsp page and add the registration form and login form for the index.jsp page

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>SSM</title>
</head>
<body>
    <a href="/user/findAllUser">Query user</a>
    <hr>
    <form method="post" action="/user/insertUser">
        User:<input type="text" name="username"><br>
        password:<input type="text" name="password"><br>
        <input type="submit" value="register"><br>
    </form>
    <hr>
    <form method="post" action="/user/login">
        User:<input type="text" name="username"><br>
        password:<input type="text" name="password"><br>
        <input type="submit" value="Sign in"><br>
    </form>
    <hr>
</body>
</html>

[3] Modify the user query jump page user.jsp to display the query data on the page

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>SSM</title>
</head>
<body>
    <h3>Query all users!</h3>
    ${userList}
</body>
</html>

[4] Create registration success reminder page: Register_ success.jsp,regist_failed.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>SSM</title>
</head>
<body>
    <h3>Registration succeeded!</h3>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>SSM</title>
</head>
<body>
    <h3>Registration failed!</h3>
</body>
</html>

[5] Create login success and login failure reminder page: login_success.jsp,login_failed.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>SSM</title>
</head>
<body>
    <h3>Login succeeded!</h3>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>SSM</title>
</head>
<body>
    <h3>Login failed!</h3>
</body>
</html>

[6] Run the Tomcat server, click "query user" to query the user, and enter the user name and password to log in and register

7. SSM integrated directory structure

Keywords: Mybatis Spring Spring MVC SSM

Added by alex57 on Thu, 14 Oct 2021 22:57:57 +0300