Spring boot blog system background login and interceptor configuration

The logic of login is very simple. You only need to make corresponding judgment according to the incoming user name and password and match the data in the database

Basic realization

1. In the controller layer, first make a non empty judgment on the incoming user name and password, and then call the Service layer for database matching. If the matching is successful, the user information will be saved in the session domain, and redirected to the admin/index request, and the index page will be returned
Mainly, because form submission is involved here, you must use redirection request to forward and return to index page directly when you jump to another page. Because browser address does not change, repeated submission will occur when refreshing
Request forwarding and redirection

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @GetMapping
    public String loginPage(){
        return "admin/login";
    }
@GetMapping({ "/index", "/index.html"})
    public String index(HttpServletRequest request) {
        return "admin/index";
    }

    @PostMapping(value = "/login")
    public String login(String userName,
                        String password,
                        HttpSession session) {
        System.out.println(userName);
        System.out.println(password);
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            session.setAttribute("errorMsg", "User name or password cannot be empty");
            return "admin/login";
        }
        AdminUser adminUser = adminService.login(userName, password);
        if (adminUser != null) {
            session.setAttribute("loginUser", adminUser.getNickName());
            session.setAttribute("loginUserId", adminUser.getAdminUserId());
            //The session expiration time is set to four hours
            session.setMaxInactiveInterval(60 * 60 * 4);
            return "redirect:/admin/index";
        } else {
            System.out.println("Landing failed");
            session.setAttribute("errorMsg", "Landing failed");
            return "admin/login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("loginUserId");
        request.getSession().removeAttribute("loginUser");
        request.getSession().removeAttribute("errorMsg");
        return "admin/login";
    }
}

2. service layer
Because the password stored in the database needs to be encrypted by MD5, the password passed in should be MD5 converted before database comparison

@Override
    public AdminUser login(String userName, String password) {
        String passwordMd5 = MD5Utils.code(password);
        return adminUserMapper.getUser(userName, passwordMd5);
    }

MD5Utils

public class MD5Utils {
    public static String code(String str){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[]byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
                i = byteDigest[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32 bit encryption
            return buf.toString();
            // 16 bit encryption
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }

    }
}

3. dao level

AdminUser getUser(@Param("userName") String userName, @Param("password") String password);
<select id="getUser" resultType="com.javaer.myblog.entity.AdminUser">
        select * from admin_user where login_user_name = #{userName,jdbcType=VARCHAR} AND login_password=#{password,jdbcType=VARCHAR} 
</select>

Interceptor configuration

The reason why interceptors are configured is that all our backstage pages are requested by / Admin, and we want to be accessible only when we log in, but at present, we can access them only when we know that others know our corresponding request address, and we need to block all requests under / admin before we can release them after judging whether they are logged in or not
The judgment of whether to log in here is realized by judging that there is corresponding user information in the session domain. When we log in again, we store the user information in our session domain, and all users with corresponding information are the logged in users
Interceptor

@Component
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String uri = request.getRequestURI();
        if (uri.startsWith("/admin") && null == request.getSession().getAttribute("loginUser")) {
            System.out.println("wrong");
            request.getSession().setAttribute("errorMsg", "Please login again");
            response.sendRedirect("/admin");
            return false;
        } else {
            request.getSession().removeAttribute("errorMsg");
            return true;
        }
    }

}

Configuring Interceptors

package com.javaer.myblog.config;

import com.javaer.myblog.interceptor.AdminLoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyBlogWebMvcConfigurer implements WebMvcConfigurer {
    @Autowired
    private AdminLoginInterceptor adminLoginInterceptor;

    public void addInterceptors(InterceptorRegistry registry) {
        // Add an interceptor to intercept the url path prefixed with / admin
        registry.addInterceptor(adminLoginInterceptor)
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin")//Release /admin
                .excludePathPatterns("/admin/login")//Release/admin/login
                .excludePathPatterns("/admin/dist/**")
                .excludePathPatterns("/admin/plugins/**");
    }

}
72 original articles published, praised 0 and visited 1751
Private letter follow

Keywords: Session Database Java

Added by Nilpez on Wed, 05 Feb 2020 07:45:10 +0200