[Spring Boot] Web Development - Interceptor

interceptor

Interceptors are very common in web systems and are generally used to intercept user requests to implement functions such as access control, logging, and sensitive filtering. This section first introduces the application scenarios of interceptors in actual projects, and then introduces how to realize the functions of custom interceptors.

1. Application scenarios

Interceptors are very common in actual application development. For some global and unified operations, we can extract them into interceptors. To sum up, interceptors generally have the following usage scenarios:

1) Permission check: such as login detection, enter the handler to check whether you are logged in, if not, return to the login page directly.

2) Performance monitoring: Sometimes the system is inexplicably slow for a certain period of time. You can record the start time before entering the processing program through the interceptor, and record the end time after processing, so as to get the processing time of the request (if there is a reverse proxy, Such as Apache, can automatically record).

3) General behavior: read the cookie to get the user information and put the user object into the request, so as to facilitate the use of subsequent processes, and extract Locale, Theme information, etc., as long as it is required by multiple processing programs, it can be implemented using an interceptor .

4) OpenSessionInView: such as Hibernate, open the Session (session) when entering the handler, and close the Session after completion.

2. Introduction to HandlerInterceptor

Spring Boot defines the HandlerInterceptor interface to implement the function of custom interceptors. The HandlerInterceptor interface defines three methods: preHandle, postHandle, and afterCompletion. By rewriting these three methods, operations such as pre-request and post-request are implemented.

1) preHandle: The preprocessing callback method realizes the preprocessing of the handler (such as login check), and the third parameter is the handler of the response.

Return value: true means to continue the process (such as calling the next interceptor or handler); false means the process is interrupted (such as the login check fails), and will not continue to call other interceptors or handlers. At this time, a response needs to be generated through response .

2) postHandle: Post-processing callback method, which implements the post-processing of the handler (but before rendering the view). At this time, the model data or the view can be processed through modelAndView (model and view objects), and modelAndView may also be null .

3) afterCompletion: Callback method after the entire request is processed, that is, callback when the view is rendered. For example, in performance monitoring, you can record the end time here and output the consumption time, and you can also perform some resource cleaning, similar to try-catch- finally in finally, but only calls the handler to execute preHandle, and returns the afterCompletion of the interceptor corresponding to true.

Sometimes we only need to implement one of the three callback methods. If we implement the HandlerInterceptor interface, we must implement the three methods regardless of whether we need them. At this time, Spring provides a HandlerInterceptorAdapter adapter (an implementation of the adapter design pattern), allowing us to only implement The required callback method.

3. Use HandlerInterceptor to implement interceptors

When we access certain pages that require authorization, such as order details, order lists, and other functions that require users to log in to view, we need to intercept these requests, perform login detection, and only allow requests that meet the rules. Next, the example of login status detection demonstrates the use of interceptors.

First, create a custom login interceptor, the sample code is as follows:

public class LoginInterceptor implements HandlerInterceptor {
    
    
    /*注册拦截器*/
    public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        Object user = request.getSession().getAttribute("user");
        if (user == null){
    
    
        request.setAttribute("msg","您没有权限这么做!");
        request.getRequestDispatcher("/").forward(request,response);
        	return false;
        }
        return true;
    }
}

In the above example, LoginInterceptor inherits the HandlerInterceptor interface, implements the preHandle interface, and verifies the user's Session status. If the current user has login information, you can continue to access; if the current user does not have login information, return No permission.

Then, inject the interceptor into the system configuration.

Define the MyMvcConfig configuration class and inject the LoginInterceptor interceptor defined above into the system. The sample code is as follows:

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(new LoginInterceptor())
        .addPathPatterns("/**").excludePathPatterns("/", "/user/login", "/asserts/**", "/webjars/**");
    }
}

Inject the newly customized LoginInterceptor interceptor into the system through the addInterceptors method of the WebMvcConfigurer class.

addPathPatterns defines the intercepted request address.

The function of excludePathPatterns is to exclude certain addresses from being blocked, for example, the login address /user/login does not require login verification.

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/131909776