springboot web development login interceptor

In SpringBoot we can use the HandlerInterceptorAdapter adapter to implement our own interceptor. In this way, all requests can be intercepted and processed accordingly.

Application scenarios

  • Logging can record the log of request information for information monitoring, information statistics, etc.
  • Permission check: such as login detection, enter the processor to check whether you are logged in, and if not, return directly to the login page.
  • Performance monitoring: typically slow logs.

The following methods are mainly provided in HandlerInterceptorAdapter:

  • preHandle: executed before the method is called. In this method, functions similar to verification can be performed. If true is returned, continue calling the next interceptor. If false is returned, execution is interrupted, which means that the method we want to call will not be executed, but you can modify the response to the response you want.
  • postHandle: called after the method is executed.
  • afterCompletion: Callback after the entire request is processed, that is, the view is rendered or the caller has received the response.

HandlerInterceptor

public interface HandlerInterceptor {
    
    
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        return true;
    }

    default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    
    
    }

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

AsyncHandlerInterceptor

public interface AsyncHandlerInterceptor extends HandlerInterceptor {
    
    
    default void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
    }
}

abstract class HandlerInterceptorAdapter

public abstract class HandlerInterceptorAdapter implements AsyncHandlerInterceptor {
    
    
    public HandlerInterceptorAdapter() {
    
    
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    
    
    }

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

    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
    }
}

Seeing the relationship between these three classes and interfaces, we understand that integrating HandlerInterceptorAdapter is just to allow us to rewrite only the methods we need. If we need to rewrite them all, we can also directly implement the interface

The running process is summarized as follows:

  • The order of interceptor execution is determined by the order defined in the Spring configuration file.
  • The preHandle methods of all interceptors will be executed in order until return false is encountered. For example, if the second preHandle method is return false, the third and subsequent interceptors will not be executed. If they all return true, the preHandle methods are loaded in order.
  • Then execute the main method (your own controller interface). If an exception is thrown in the middle, the effect is the same as return false. PostHandle will not continue to be executed, but the afterCompletion method will be executed in reverse order.
  • After the main method has finished executing the business logic (the page has not yet rendered data), the postHandle method is executed in reverse order. If the preHandle method of the third interceptor returns false, the second and first postHandle methods and afterCompletion will be executed (this will only be executed after postHandle is executed, that is, after the page has rendered the data, after will be executed to clean up the work) )method. (postHandle and afterCompletion are executed in reverse order)

Write an interceptor

public class LoginInterceptor extends HandlerInterceptorAdapter {
    
    
    Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        System.out.println("==============LoginInterceptor========preHandle==========");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    
    
        System.out.println("==============LoginInterceptor======postHandle============");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    
    
        System.out.println("==============LoginInterceptor=======afterCompletion===========");
    }
    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        System.out.println("==============LoginInterceptor========afterConcurrentHandlingStarted==========");
    }

}

public class LoginInterceptor2 extends HandlerInterceptorAdapter {
    
    
    Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        System.out.println("==============LoginInterceptor2========preHandle==========");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    
    
        System.out.println("==============LoginInterceptor2======postHandle============");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    
    
        System.out.println("==============LoginInterceptor2=======afterCompletion===========");
    }
    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        System.out.println("==============LoginInterceptor2========afterConcurrentHandlingStarted==========");
    }

}

The WebMvcConfigurerAdapter abstract class is a simple abstraction of the WebMvcConfigurer interface (adding some default implementations), but WebMvcConfigurerAdapter has been abandoned in Spring Boot 2.0 and Spring 5.0. It is officially recommended to directly implement WebMvcConfigurer or directly inherit WebMvcConfigurationSupport

Implement WebMvcConfigurer configuration interceptor

@Configuration
public class SpringMVCConfig implements WebMvcConfigurer {
    
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(new LoginInterceptor());
        registry.addInterceptor(new LoginInterceptor2());
    }
}

Insert image description here

Verify it yourself in the "Operation Process Summary" above, but I won't go into too much detail.

Guess you like

Origin blog.csdn.net/wufagang/article/details/107630082