SpringBoot implements login interceptor

For management systems or other systems that require user login, login verification is an indispensable link. In the project developed by SpringBoot, user login interception and verification are achieved by implementing interceptors.

1. The principle of SpringBoot's implementation of login interception

SpringBoot HandlerInterceptorimplements the interceptor by implementing the WebMvcConfigurerinterface, implements a configuration class by implementing the interface, injects the interceptor into the configuration class, and finally injects the configuration through the @Configuration annotation.

1.1, implement the HandlerInterceptorinterface

Implement HandlerInterceptorthe interface need to implement three preHandlemethods: postHandle, , afterCompletion.

The functions of each of the three methods are as follows:

package blog.interceptor;

import blog.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class UserLoginInterceptor implements HandlerInterceptor {
    
    

    /***
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        System.out.println("执行了拦截器的preHandle方法");
        try {
    
    
            HttpSession session = request.getSession();
            //统一拦截(查询当前session是否存在user)(这里user会在每次登录成功后,写入session)
            User user = (User) session.getAttribute("user");
            if (user != null) {
    
    
                return true;
            }
            response.sendRedirect(request.getContextPath() + "login");
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return false;
        //如果设置为false时,被请求时,拦截器执行到此处将不会继续操作
        //如果设置为true时,请求将会继续执行后面的操作
    }

    /***
     * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
    
        System.out.println("执行了拦截器的postHandle方法");
    }

    /***
     * 整个请求结束之后被调用,也就是在DispatchServlet渲染了对应的视图之后执行(主要用于进行资源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    
    
        System.out.println("执行了拦截器的afterCompletion方法");
    }
}

preHandleIt is executed before the Controller, so the function of the interceptor is mainly implemented in this part:

  1. Check whether there is an userobject in the session ;
  2. If it exists, return true, and then the Controller will continue the subsequent operation;
  3. If it does not exist, it will be redirected to the login interface. It
    is through this interceptor that the Controller will be executed before it is executed preHandle.

1.2. Implement the WebMvcConfigurerinterface and register the interceptor

Implement the WebMvcConfigurerinterface to implement a configuration class, and register an object of the interceptor implemented above to this configuration class.

package blog.config;

import blog.interceptor.UserLoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class LoginConfig implements WebMvcConfigurer {
    
    

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        //注册TestInterceptor拦截器
        InterceptorRegistration registration = registry.addInterceptor(new UserLoginInterceptor());
        registration.addPathPatterns("/**"); //所有路径都被拦截
        registration.excludePathPatterns(    //添加不拦截路径
                "/login",                    //登录路径
                "/**/*.html",                //html静态资源
                "/**/*.js",                  //js静态资源
                "/**/*.css"                  //css静态资源
        );
    }
}

Register the interceptor in the interceptor list, and specify which access paths are blocked, which access paths are not blocked, and which resource files are not blocked; finally, the configuration is injected with the @Configuration annotation.

1.3, keep logged in

You only need to log in once. If you have logged in, you do not need to log in again when you visit again next time, you can directly access the content of the website.

After the correct login, it will be usersaved sessionin. When the page is accessed again, the login interceptor can find this userobject, and there is no need to intercept the login interface again.

@RequestMapping(value = {
    
    "", "/", "/index"}, method = RequestMethod.GET)
public String index(Model model, HttpServletRequest request) {
    
    
    User user = (User) request.getSession().getAttribute("user");
    model.addAttribute("user", user);
    return "users/index";
}

@RequestMapping(value = {
    
    "/login"}, method = RequestMethod.GET)
public String loginIndex() {
    
    
    return "users/login";
}

@RequestMapping(value = {
    
    "/login"}, method = RequestMethod.POST)
public String login(@RequestParam(name = "username")String username, @RequestParam(name = "password")String password,
                    Model model, HttpServletRequest request) {
    
    
    User user = userService.getPwdByUsername(username);
    String pwd = user.getPassword();
    String password1 = MD5Utils.md5Code(password).toUpperCase();
    String password2 = MD5Utils.md5Code(password1).toUpperCase();
    if (pwd.equals(password2)) {
    
    
        model.addAttribute("user", user);
        request.getSession().setAttribute("user", user);
        return "redirect:/index";
    } else {
    
    
        return "users/failed";
    }
}

2. Code implementation and examples

The code implementation is shown above.

After the login is successful, save the userinformation sessionin, the next time you log in, the browser SESSIONIDcan find the corresponding according to your own session, so don't log in again, you can see it in the Chrome browser.
Insert picture description here

3. Effectiveness verification

3.1. Visit the localhost:8081/index page:

Insert picture description here
Was redirected to localhost:8081/login, which realized login interception.

3.2. Enter the user name and password correctly to log in

Insert picture description here

3.3, visit localhost:8081/index again

Insert picture description here
It is not intercepted by the login interceptor again, which proves that the login can be maintained.

Guess you like

Origin blog.csdn.net/qq_27198345/article/details/111401610