2022 new version of graphic explanation SpringBoot integration SSM framework (with source code)

Copyright notice

  • Original author of this article: brother Gu's younger brother
  • Author blog address: http://blog.csdn.net/lfdfhl

Tutorial overview

This tutorial explains in detail the process, specific steps and precautions of SpringBoot integrating SSM framework in graphic form.

Data preparation

Here, prepare the database, data table and data required for this tutorial; Details are as follows:

DROP DATABASE IF EXISTS crmsb;
-- Create database crmsb
CREATE DATABASE crmsb;
-- Select database crmsb
USE crmsb;

-- Create user table
CREATE TABLE user (
  id int(32) NOT NULL AUTO_INCREMENT COMMENT 'user id',
  username varchar(32) NOT NULL COMMENT 'User name',
  nickname varchar(64) NOT NULL COMMENT 'User nickname',
  password varchar(32) NOT NULL COMMENT 'User password',
  state char(1) NOT NULL COMMENT '1:normal,0:invalid',
  PRIMARY KEY (id)
);

-- Insert data into user table
INSERT INTO user (username,nickname,password,state) VALUES ('zxx', 'Xing Xing Zhou', '123456', '1');
INSERT INTO user (username,nickname,password,state) VALUES ('zxc', 'Zhou Xingchi', '123456', '1');
INSERT INTO user (username,nickname,password,state) VALUES ('blx', 'Bao Longxing', '123456', '1');
INSERT INTO user (username,nickname,password,state) VALUES ('sqe', 'Su Qier', '123456', '1');

-- Query data from user table
SELECT * FROM user;

Create a SpringBoot project

Here, I will introduce in detail the process and main steps of using Spring Initializr to build a SpringBoot project in IDEA.

Create a new project, as shown below:

Use Spring Initializr to create Spring Boot project CRMSB, as shown below:

Summary of key points:

  • 1. Check Spring Web add dependency under Web. In fact, you can also check other dependencies in this step. If you don't check here, you need to follow up in POM Add dependencies to the XML file.
  • 2. Spring Boot 2.6.7 indicates the latest stable version


Click Finish to create the SpringBoot project, as shown below:

Start the project and check whether the project can be started normally; The diagram is as follows:

Integrate SSM framework

In the previous operation, we completed the creation of the basic SpringBoot project in the IDEA. Next, we integrate the three SSM frameworks on this basis.

Add dependency

After project initialization, POM The XML file contains some dependencies, as shown below:

Here, we need to add the dependencies commonly used in SSM projects to < dependencies > < / dependencies >. Common ones are MySQL, druid, pagehelper, MyBatis, jackson, jstl, etc; Details are as follows:

    <dependencies>
        <!--web rely on-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--test rely on-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--MySQL rely on-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!--druid rely on-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <!--MyBatis rely on-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <!--Paging dependency-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.1</version>
        </dependency>
        <!--jsp Resolve dependency-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!--jstl rely on-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!--Hot deployment dependency-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <!--jackson rely on-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.1</version>
        </dependency>
    </dependencies>

create package

Here, prepare the packages that may be used in the project in advance.

Create packages related to Java code

First, please click com. Com under the java package cn. Create the code in the java package related to MSB; Common are: config, controller, pojo, service, mapper, interceptor, utils, etc; The diagram is as follows:


matters needing attention:

The startup class CrmsbApplication of SpringBoot project has a parallel relationship with java packages. Do not place CrmsbApplication in any package.

Create packages related to resources code

Please create com.com in the form of com/cn/crmsb/mapper under resources cn. crmsb. The mapper package is used to store mapper mapping files.

matters needing attention:

  • 1. Do not use COM cn. crmsb. Mapper package is created in the way of mapper
  • 2. The package name of the mapper mapping file must be consistent with the package name of the package where the mapper interface file is located

The diagram is as follows:

Create webapp related folders

Please create a webapp folder related to page resources under the main package, and copy the static resources (css, fonts, imgs, js, etc.) and jsp pages required by the project to webapp; The diagram is as follows:

Write configuration file

Here, improve the project configuration file application Properties.

Summary of key points:

  • 1. Please pay attention to the package name in the configuration file. Please set it according to the actual situation of the project
  • 2. Please pay attention to the path in the configuration file. Please set it according to the actual situation of the project
  • 3. Please pay attention to the configuration information in the configuration file. Please set it according to the actual situation of the project
  • 4. Please pay attention to the red mark in the screenshot. Please set it according to the actual situation of the project

application. The source code of properties is as follows:

# configure port
server.port=9090
# Configuration item name
server.servlet.context-path=/
# Open jsp template development mode
server.servlet.jsp.init-parameters.development=true
# Specify the view prefix (directory name)
spring.mvc.view.prefix=/views/
# Specify view suffix
spring.mvc.view.suffix=.jsp
# Configure MySQL database and data source
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/crmsb?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# Specifies the path of the project static resource
spring.web.resources.static-locations= classpath:/
# Specify the storage location of mapper mapping file
mybatis.mapper-locations=classpath:com/cn/crmsb/mapper/*.xml
# Configure the package that MyBatis alias works on
mybatis.type-aliases-package=com.cn.crmsb.pojo
# Configuration log
logging.level.root=info
logging.level.com.cn.crmsb=debug
# Configure paging
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql
# Configuration file upload
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=50MB


The information that needs to be configured according to the actual situation is as follows:


Write the code of each layer

Next, we write the code according to the layered idea and take user login as an example.

User class

Please create User class under pojo package.

As a JavaBean, the attribute name of the user class should be consistent with the field of the user table in the database.

package com.cn.crmsb.pojo;
/**
 * Author: brother Gu's younger brother
 * Blog address: http://blog.csdn.net/lfdfhl
 */
public class User {
    private Integer id;
    private String username;
    private String nickname;
    private String password;
    private String role;

    public User() {
        super();
    }

    public User(Integer id, String username, String nickname, String password, String role) {
        this.id = id;
        this.username = username;
        this.nickname = nickname;
        this.password = password;
        this.role = role;
    }

    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 getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getPassword() {
        return password;
    }

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

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

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

UserMapper interface file

Please create a UserMapper interface file under the mapper package java.

Summary of key points:

  • 1. Define the method queryUserByUsernameAndPassword() in this interface
  • 2. Use @ Repository annotation on UserMapper interface
package com.cn.crmsb.mapper;

import com.cn.crmsb.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
 * Author: brother Gu's younger brother
 * Blog address: http://blog.csdn.net/lfdfhl
 */

@Repository
public interface UserMapper {
    //Pass parameters to MyBatis with @ Param annotation
    User queryUserByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
}

UserMapper mapping file

Please visit com.com in resources cn. crmsb. Create a UserMapper mapping file under the mapper package xml.

Summary of key points:

  • 1. The mapping file name is consistent with the mapping interface name, both of which are UserMapper; However, the suffix is different
  • 2. The namespace attribute value in the mapping file is the interface file usermapper Full pathname of Java
  • 3. The id attribute value of the select tag is the interface file usermapper Method name queryUserByUsernameAndPassword in Java
  • 4. The parameterType property value of the select tag is the input parameter type of the queryUserByUsernameAndPassword method
  • 5. The resultType attribute value of the select tag is the return value type of the queryUserByUsernameAndPassword method; However, its initial is lowercase.
  • 6. Use placeholders in the select tag to write SQL statements
<?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.cn.crmsb.mapper.UserMapper">
    <!-- Query user -->
    <select id="queryUserByUsernameAndPassword" parameterType="String" resultType="user">
        select * from user where username = #{username} and password = #{password}
    </select>
</mapper>

UserService

Please create UserService interface under service package.

Please create the impl sub package under the service package and create the implementation class UserServiceImpl of the UserService interface under the impl package.

Summary of key points:

  • 1. Declare the queryUserByUsernameAndPassword() method in the UserService interface
  • 2. Use @ Service annotation on UserServiceImpl class
  • 3. Use the @ Transactional annotation on the UserServiceImpl class
  • 4. Inject UserMapper with @ Autowired in UserServiceImpl class
  • 5. Call the queryUserByUsernameAndPassword() method of UserMapper in the queryUserByUsernameAndPassword() method of UserServiceImpl class

The UserService interface is as follows:

package com.cn.crmsb.service;

import com.cn.crmsb.pojo.User;

import java.util.List;
/**
 * Author: brother Gu's younger brother
 * Blog address: http://blog.csdn.net/lfdfhl
 */
public interface UserService {
    //Query user
    User queryUserByUsernameAndPassword(String username, String password);
}

UserServiceImpl class is as follows:

package com.cn.crmsb.service.impl;

import com.cn.crmsb.mapper.UserMapper;
import com.cn.crmsb.pojo.User;
import com.cn.crmsb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * Author: brother Gu's younger brother
 * Blog address: http://blog.csdn.net/lfdfhl
 */

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    //Query user
    @Override
    public User queryUserByUsernameAndPassword(String username, String password) {
        User user = userMapper.queryUserByUsernameAndPassword(username, password);
        return user;
    }

}

UserController

Please create UserController under controller package.

Summary of key points:

  • 1. Use the @ Controller annotation and @ RequestMapping annotation on the UserController class
  • 2. Inject UserService with @ Autowired in the UserController class
  • 3. Define the login() method in the UserController class
  • 4. Use the @ RequestMapping annotation on the login() method
  • 5. Call the queryUserByUsernameAndPassword() method of UserService in the login() method
  • 6. After successful login, save the user information to session
  • 7. The return value of the login() method is the path to the jump page
  • 8. After successful login, jump to the ok page
  • 9. After the login fails, jump to the login page
package com.cn.crmsb.controller;

import com.cn.crmsb.pojo.User;
import com.cn.crmsb.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
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 org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.List;
/**
 * Author: brother Gu's younger brother
 * Blog address: http://blog.csdn.net/lfdfhl
 */

@RequestMapping("userController")
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    //Sign in
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String login(String username, String password, Model model, HttpSession session) {
        User user = userService.queryUserByUsernameAndPassword(username, password);
        System.out.println("user="+user);
        if (user != null) {
            // Save current USER to Session
            session.setAttribute("USER", user);
            // Redirect to customer list page
            // return "redirect:/customerController/list";
            // Redirect to login success page loginSuc
            return "ok";
        }
        model.addAttribute("msg", "The account or password is wrong, please re-enter!");
        // Return to login page
        return "login";
    }


}

login page

Login in views under webapp package The JSP page is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
    <title>CRM User login</title>
    <meta http-equiv=Content-Type content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- ${pageContext.request.contextPath} express /CRM -->
    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <!-- jQuery (Bootstrap All JavaScript All plug-ins depend on jQuery,So it must be put in front) -->
    <script src="https://fastly.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"
            integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
            crossorigin="anonymous"></script>
    <!-- load Bootstrap All JavaScript plug-in unit. You can also load only a single plug-in as needed. -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
            integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
            crossorigin="anonymous"></script>

    <link href="https://fastly.jsdelivr.net/npm/@bootcss/v3.bootcss.com@1.0.31/examples/signin/signin.css"
          rel="stylesheet">

    <script>
        // Verify whether the user and password are empty
        function checkLogin() {
            var username = $("#inputUsername").val();
            var password = $("#inputPassword").val();
            if (username == "" || password == "") {
                $("#Message ". Text (" user and password cannot be empty! ");
                return false;
            }
            return true;
        }
    </script>
</head>
<body>
<div class="panda_container">
    <div class="panda_login_form">

        <div class="container">

            <form class="form-signin" action="${pageContext.request.contextPath}/userController/login" method="post"
                  onsubmit="return checkLogin()">
                <h2 class="form-signin-heading text-center">CRM</h2>
                <br>
                <!-- Prompt information -->
                <p><span id="message" style="color: red">${msg}</span></p>
                <label for="inputUsername" class="sr-only">user name</label>
                <input type="text" id="inputUsername" name="username" class="form-control" placeholder="enter one user name"
                       autofocus>
                <p></p>
                <label for="inputPassword" class="sr-only">password</label>
                <input type="password" id="inputPassword" name="password" class="form-control" placeholder="Please input a password">
                <br>
                <button class="btn btn-lg btn-primary btn-block" type="submit">land</button>
                <a class="btn btn-link btn-block" href="#"> registration</a>
            </form>
        </div>
    </div>
</div>
</body>
</html>

ok page

OK in views under webapp package The JSP page is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
    <title>OK</title>
</head>
<body>
  <h1>Login OK</h1>
</body>
</html>

Configure the SpringBoot project startup class

After completing the coding of each layer, we will configure the startup class CrmsbApplication of SpringBoot project.

Please scan mapper interface file with @ MapperScan annotation on CrmsbApplication class.

package com.cn.crmsb;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * Author: brother Gu's younger brother
 * Blog address: http://blog.csdn.net/lfdfhl
 */

@SpringBootApplication
@MapperScan("com.cn.crmsb.mapper")
public class CrmsbApplication {

    public static void main(String[] args) {
        SpringApplication.run(CrmsbApplication.class, args);
    }

}

Deployment and testing

Please click the green button in CrmsbApplication class to run the project, as shown below:


After the project is started, please enter in the browser http://localhost:9090/views/login.jsp Log in.

Test information:

  • 1. User name zxc
  • 2. Password 123456


After successful login, jump to OK jsp; The diagram is as follows:

summary

Generally speaking, it is not difficult to integrate SSM framework with SpringBoot in IDEA; However, there are many details that need to be paid attention to. Therefore, in the process of integration, we must be careful, thoughtful and patient.

Tags: Java Spring Boot IDEA

Posted by polandsprings on Thu, 12 May 2022 23:13:42 +0300