SpringBoot: implement users to log in to different pages according to their roles

This article records the simple process of user login with SpringBoot, which is very difficult for me to get started, so I will feature this article after the login. Describe the problems and doubts I encountered in the process of implementation, which is also my own learning notes!!

Development environment:

  • IDE: JetBrains Intelij IDEA
  • Java: JavaSE13
  • SpringBoot + xadmin + Layui +Mybatis + MySQL

Detailed process:

File directory:

The directory used to realize the user login function has been marked:

  • The [domain] directory is mainly used for Entity and Repository control
  • The service layer is mainly business code
  • [controller] is responsible for page access control
  • Database access layer
  • [entity] entity layer (not here)
Set up and connect to the database:
set up a database

Set up a database in Navicat and a user table (used to store the users to log in)

The user login mainly uses the following user table, where the user name and password are entered in advance.

set up application.properties file

Then, open the application.properties File, configure the following information:

# Connection driver of database
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# The address of the database to be connected. Pay attention to the port and the name of the database to be connected, and then set the time zone. Otherwise, an error may be reported
spring.datasource.url=jdbc:mysql://localhost:3306/database-manager?serverTimezone=UTC
# Connected account and password, according to your own situation
spring.datasource.username=root
spring.datasource.password=123456

# The following about mybatis should be set. Otherwise, an error will be reported and the database data cannot be read.
# mapper xml file path
mybatis.mapper-locations=classpath:mapper/*.xml
# Entity class alias
mybatis.type-aliases-package=pinksmile.database.domin
# Turn on hump naming
mybatis.configuration.map-underscore-to-camel-case=true
# Output log to console
mybatis.configuration.logImpl=org.apache.ibatis.logging.stdout.StdOutImpl
# The development configuration is false to avoid changing the template and restarting the server
spring.thymeleaf.cache=false

Then, use IDEA to connect to the database:

Using Mybatis to operate the database

Configure database data operations UserMapper.xml File: note the association with dao layer and domain layer.
What should be noted is marked below (there are articles on the Internet):

<?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">
<!--author PinkSmile User table-->
<mapper namespace="pinksmile.database.dao.UserDao">
    <resultMap id="UserMap" type="pinksmile.database.domain.User">
        <result column="id" javaType="Integer" jdbcType="INTEGER" property="id"/>
        <result column="nickname" javaType="String" jdbcType="VARCHAR" property="nickname"/>
        <result column="username" javaType="String" jdbcType="VARCHAR" property="username"/>
        <result column="password" javaType="String" jdbcType="VARCHAR" property="password"/>
        <result column="permission" javaType="String" jdbcType="VARCHAR" property="permission"/>
        <result column="role" javaType="String" jdbcType="VARCHAR" property="role"/>
    </resultMap>
    <!--Get users from the table by user name and password-->
    <select id="login" resultType="pinksmile.database.domain.User">
        select * from user where username = #{username} and password = #{password}
    </select>

    <!--Through users id Get user role-->
    <select id="getUserRoleByID" resultType="String">
        select role from user where id = #{userId}
    </select>
</mapper>

At this point, the database has been configured. Write the code below.

Prepare page:

templates Directory:

  • login.html Login page
  • index.html Page that ordinary users jump to after login
  • manage.html The page that the administrator jumps to after logging in

Documents and functions of each layer

First of all, in domain User.java , which is used as the mapping of database tables and describes the information of tables in the database:

This file should pay attention to the download of lombok dependency, which can be completed by using the extension plug-in of IDEA, and the method can refer to the Internet.

package pinksmile.database.domain;

import lombok.Data;

/**
 * Logged in users table
 * @author PinkSmile
 */
@Data
public class User {
    /**
     * Fields marked by database users
     * Ensure that the fields and data types are consistent
     */
    private Integer id;
    private String nickname;
    private String username;
    private String password;
    private String permission;
    private String role;
}
Database interface of [dao] layer:

Function interface and previous configuration of this layer UserMapper.xml File, this file is to provide the interface, and that configuration file is to implement the function of the interface.

package pinksmile.database.dao;

import org.springframework.stereotype.Repository;
import pinksmile.database.domain.User;

@Repository      // This is the database of mybatis operation
public interface UserDao {
    // Get user information according to user name and password
    User login(String username, String password);
    // Get user role according to user id
    String getUserRoleByID(Integer userId);
}
[service] business logic writing

After initializing the database environment and defining the database provider, the following is the writing of business logic.

package pinksmile.database.service;

import org.springframework.data.relational.core.sql.In;
import pinksmile.database.dao.UserDao;
import pinksmile.database.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    // Log in based on user name and password
    public User login(String username, String password) {
        return userDao.login(username, password);
    }
    // Get user role through user ID
    public String getUserRoleByID(Integer userId) {return  userDao.getUserRoleByID(userId);}
}

[controller] is responsible for page access control

This layer is the most troublesome one, responsible for page Jump and various activities of the page.

First, log in page control

Note: I didn't make a clear distinction between the use of web address and web page at the beginning. Each page corresponds to a web address.
Business logic:

  • Enter web address http://localhost:8080/login enters the login page, which is what we wrote login.html Front page.
  • If you are already logged in, redirect to the management interface http://localhost:8080/manage, jump to different interfaces according to different user roles
  • If you are not logged in, return to the login page.
  • If the login is successful, the URL of the failed page is http://localhost:8080/manage/verification, but the displayed page is still the login page.
  • If the login is successful, go to the management page.
BackManage.java

Implementation function:

  • Manage the mapping between page and web address, and jump to the page after login
package pinksmile.database.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import pinksmile.database.domain.User;
import pinksmile.database.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class BackManage {
    @Autowired
    UserService userService;
    /**
     * Background management page data preparation interface
     * @param request Used to get Session to determine whether to log in
     * @return Back to template page
     */
    @GetMapping("/manage")      // Administration page URL
    public String manage(HttpServletRequest request){

        HttpSession session=request.getSession();       // Get login information
        Object obj = session.getAttribute("user");
        // No login, return to login page
        if(obj == null){     // The login information is null, indicating no login
            return "redirect:/login";
        }

        User loginUser = (User) obj;                    // Cast to User
        Integer userId = loginUser.getId();             // Get the id of the logged in user

        String role = userService.getUserRoleByID(userId);      // Get the user's role by logging in the user's id
        // If the user logs in, return to the user interface
        if (role.equals("user")){
            return "index";
        }
        // If the administrator logs in, return to the management page
        return "manage";
    }

    @GetMapping("/welcome")
    public String toWelcome() {return "welcome";}
}
Login.java:

Implementation function:

  • Get password from database to log in
  • Every time you arrive at the login page, judge whether you have logged in in a short time, and jump to the page directly after logging in
package pinksmile.database.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import pinksmile.database.domain.User;
import pinksmile.database.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class Login {
    @Autowired
    UserService userService;

    /**
     * Used to return to the login page
     * @param request Judge whether it has been logged in, and jump directly after it has been logged in
     * @return  Return to login page template
     */
    @GetMapping("/login")  // Login page URL
    public String login(HttpServletRequest request) {
        HttpSession session = request.getSession();     // Get user login information
        // If you have logged in, redirect to the judgment interface
        if (session.getAttribute("user") != null) {
            return "redirect:/manage";
        }

        // If there is no login information, return to the login page directly
        return "login";
    }

    /**
     * Used to verify whether the account and password are correct
     *
     * @param username   account information
     * @param password   Password information
     * @param request    Used to get Session
     * @return Log in successfully and jump to the management interface. If it fails, the error message will be returned to the login page
     */
    @PostMapping("/manage/verification")        // Failure error message page URL
    public String verification(@RequestParam("username") String username,
                               @RequestParam("password") String password,
                               HttpServletRequest request) {

        if (username.equals("") || password.equals("")) {   // Password is empty, log in again
            return "login";
        } else {
            User user = userService.login(username, password);  // Get the same user as the input from the database
            if (user == null) {         // There is no such user
                return "login";
            }
            // Create session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
        }

        return "redirect:/manage";             // Log in successfully and select page to jump
    }
}

Operation result:

Ordinary users log in to the background management page:

After you have logged in, log in and directly redirect to the management page:

Tags: Database Mybatis Session Spring

Posted on Tue, 09 Jun 2020 04:04:11 -0400 by markspec87