Do you understand the use of springboot interceptor Interceptor

  • 2021-11-02 01:01:33
  • OfStack

The interceptor in springmvc can judge the request and intercept the illegal request before the request reaches the controller
Let's talk about its use in springboot

There can be multiple interceptors to intercept different url
Our example assumes that if the user has logged in, the user will set up an session, and if there is user information in session, it means that the user has logged in

1. We first create an instance object of User, domain


public class User {
    private Integer id;
    private String name;
    private Integer age;
    public User() {
    }
    public User(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

2. Create an interceptor LoginInterceptor to realize HandlerInterceptor interface, and implement its method, mainly preHandle method, others can be ignored


package com.huang.interceptor;
import com.huang.domain.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 LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // You can only access it if the user has logged in 
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        if(user == null){
            response.sendRedirect(request.getContextPath()+"/user/login");
            return false;
        }else{
            return true;
        }
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

In our springmvc project, create the interceptor, and the next step is to write interceptors in the configuration file xml of springmvc > interceptor > bean class= "Full class name of interceptor"
But in springboot, we don't have to write this, we can do it by configuring classes

So we create a new configuration class InterceptorConfig to implement the WebMvcConfigurer interface


package com.huang.configure;
import com.huang.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/user/**").excludePathPatterns("/user/login","/user/logout","/user/setsession");
    }
}

Note that we're going to use an annotation @ Configuration to indicate that this is a configuration class, which springboot automatically scans at startup time
As can be seen from the above code, InterceptorRegistry is a registrar class of interceptor. Use addInterceptor (new XXXInterceptor) to register this interceptor class. addPathPatterns ("/user/**") This method is reconstructed and can accept multiple string parameters. It can also accept a collection of list, that is, matching url, and excludePathPatterns () is also reconstructed, indicating which url is excluded, that is, it does not pass through this interceptor

With the above interceptor and registration complete, we can write several method tests in the controller


package com.huang.controller;

import com.huang.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

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

    @RequestMapping(value="/login")
    @ResponseBody
    public String userlogin(){
        return " Jump to the page where the user logged in ";
    }


    @RequestMapping(value="/gomain")
    @ResponseBody
    public String goMain(){
        return " This is the page after the user enters ";
    }

    @RequestMapping(value="/logout")
    @ResponseBody
    public String logout(){
        return " This is the user logout interface ";
    }

    @RequestMapping(value="/setsession")
    @ResponseBody
    public Object setSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("user",new User(1,"huang",20));
        return "OK";
    }

}

When the user has not requested the/user/setsession, if the user has requested the/user/gomain interceptor, it will play a role and jump to the/user/login interface. If the user has requested the/user/setsession, then request the/user/gomain interceptor will be released and the corresponding result will be requested


Related articles: