Home  >  Article  >  Java  >  How to implement interceptor function in Springboot

How to implement interceptor function in Springboot

WBOY
WBOYforward
2023-05-14 10:55:183397browse

How to implement interceptor function in Springboot

preHandle: Pre-processing, processing before the target's controller method is executed

postHandle: In the target's controller method After the controller method is executed, it is processed before reaching the specified page

afterCompletion: Processed after the page is rendered

Method:

1. Springboot implements the interceptor by implementing the HandlerInterceptor interface

2. Implements a configuration class through WebMvcConfigurer, and then injects it into the container through the @Configuration annotation

3 .Specify interception rules

Taking user login as an example, if the user is not logged in and there is no user data in the session, it will be redirected to the homepage login page

After logging in correctly, Save the relister to the session. When you visit the page again, the login interceptor can find the relister object, and there is no need to intercept the login interface again.

How to implement interceptor function in Springboot

How to implement interceptor function in Springboot

package com.zwz.springbootweb.interceptor;
 
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
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;
import javax.websocket.Session;
 
public class LoginInterceptor implements HandlerInterceptor {
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object reglister = session.getAttribute("Reglister");
 
 
        if (reglister != null) {
            return true;
        } else {
            request.setAttribute("msg", "请先登录!");
 
            request.getRequestDispatcher("/").forward(request,response);
            return false;
        }
    }
 
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

Then implement a configuration class by implementing the WebMvcConfigurer interface, inject the interceptor into the configuration class, and finally inject the configuration through the @Configuration annotation. And specify the interception path and the path that needs to be released.

Note:Interceptor /** will intercept all resources, including static resources, static resources need to be released

How to implement interceptor function in Springboot

package com.zwz.springbootweb.config;
 
import com.zwz.springbootweb.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;
 
 
@Configuration
public class WebConfig implements WebMvcConfigurer{
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/loginjudge","/","/retolo","/static/**");
    }
}

Interceptor Application scenarios

1. Logging: record the log of request information for information monitoring, information statistics, calculation of PV (Page VIEW), etc.

2. Permission check: such as login detection, enter the processor to detect whether you are logged in, and if not directly return to the login page;

3. Performance monitoring: Sometimes the system behaves inexplicably during a certain period of time If it is slow, you can use the interceptor to record the start time before entering the processor, 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, it can be automatically recorded);

4. General behavior: read the cookie to obtain the user information and put the user object into the request, so as to facilitate subsequent use of the process, as well as extracting Locale and Theme information, etc., as long as it is needed by multiple processors, it can be implemented using an interceptor .

5. OpenSessionInView: Like Hibernate, open the SESSION before entering the processor and close the SESSION after completion.

The difference between interceptors and filters

1. Interceptors are based on Java's reflection mechanism, while filters are based on function callbacks.

2. The interceptor does not depend on the servlet container, but the filter depends on the servlet container.

3. Interceptors can only work on ACTION requests, while filters can work on almost all requests.

4. Interceptors can access objects in the ACTION context and value stack, but filters cannot.

5. In the life cycle of ACTION, the interceptor can be called multiple times, but the filter can only be called once when the container is initialized.

6. The interceptor can obtain each bean in the IOC container, but the filter cannot. This is very important. Injecting a service into the interceptor can call business logic.

The above is the detailed content of How to implement interceptor function in Springboot. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete