SpringBoot interceptor - Filter - listener

SpringBoot interceptor - Filter - listener

Filter application scenario

Filter can be simply understood as "take what you want", ignoring what you don't want;

1) Filter sensitive words (prevent sql injection)

2) Set character encoding

3) URL level access control

4) Compressed response information

Interceptor usage scenario

Interceptors can be simply understood as "refuse what you want" and care about what you want to refuse, such as intercepting sensitive words on a BBS forum.

The interceptor is essentially aspect oriented programming (AOP). The functions that meet the crosscutting concerns can be implemented in the interceptor. The main application scenarios include:

  • Login authentication to determine whether the user logs in.
  • Permission verification to determine whether the user has permission to access resources, such as verifying the token
  • Log record, record the request operation log (user ip, access time, etc.) in order to count the requested access.
  • Handle cookie s, localization, internationalization, themes, etc.
  • Performance monitoring, monitoring request processing time, etc.
  • General behavior: read the cookie to get user information and put the user object into the request, so as to facilitate subsequent processes. For example, extract Locale and Theme information. As long as it is required by multiple processors, it can be implemented by interceptor)

Listener application scenario

Listener: listener is a special class defined in the servlet specification. It is used to listen for creation and destruction events of domain objects such as servletContext, HttpSession and servletRequest. Listen for the event that the property of a domain object is modified.

It is used to do some necessary processing before and after the event. It can be mainly used in the following aspects:

1. Statistics of online population and online users

2. Load initialization information at system startup

3. Statistics of website visits

4. Record user access path

Create filter

// /*Filtering all requests urlPatterns can be specified using {'', ''}
@WebFilter(urlPatterns = "/*",filterName = "filter1")
public class FilterDemo1 implements Filter {  //You can create multiple filters

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter 1 starts initialization");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Filter 1 starts working");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("Filter 1 destroyed");
    }

}

Then add the @ ServletComponentScan annotation on the startup class and it will be automatically registered in the container

Create interceptor (common)

// Interceptors can define multiple
public class InterceptorDemo1 extends HandlerInterceptorAdapter {

    
     //Preprocessing, before the controller method is executed
    //If return false, the following methods will not be executed, including the methods of the controller to be executed
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        StringBuffer requestURL = httpServletRequest.getRequestURL();
        System.out.println("Front interceptor 1 preHandle:  Requested uri Is:"+requestURL.toString());

        return true; 
    }
    // Post processing
    // After executing the controller method, execute it before return ing
    //Remember that if the return value of preprocessing is false, post-processing will not be executed
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("Interceptor 1 postHandle:  ");
    }
    // Final treatment
    //    It will not be executed until the controller method is executed and return
    //    If retrun fasle is preprocessed; The final processing will not be executed
    //    But this page can't jump because it's still farting after execution. It's usually used for resource release
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("Interceptor 1 afterCompletion:  ");
    }

}

Register interceptor

@Configuration
public class InterceptorConfiguration implements WebMvcConfigurer {

    /**
     * Register custom interceptors
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //  /**It means that the execution order of intercepting all requests is related to the configuration order, that is, the configuration order first comes first
        
        //        Add interceptor
        new InterceptorDemo1();
        registry.addInterceptor(new  InterceptorDemo1() )
//                Define interception path
                .addPathPatterns("/**")
//                Define release path
                .excludePathPatterns("/index/**");
}

The handler parameter in the interceptor uses

//Controller request is required  
    if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        System.out.println("The current interception method is:"+handlerMethod.getMethod().getName());
        System.out.println("The currently intercepted method parameter length is:"+handlerMethod.getMethod().getParameters().length);
        System.out.println("The currently intercepted classes are:"+handlerMethod.getBean().getClass().getName());
        String uri = request.getRequestURI();
        System.out.println("Intercepted uri: "+uri);
        }

Create listener

There are three types of commonly used listeners

//Application start listening
@WebListener
public class ServletContextListenerDemo implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();

        System.out.println("ServletContextListenerDemo Listener initialization............");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

        System.out.println("ServletContextListenerDemo Listener destruction...........");
    }

}

//Request listening
@WebListener
public class ServletRequestListenerDemo  implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        ServletRequest servletRequest = sre.getServletRequest();
        System.out.println("ServletRequestListenerDemo Listener initialization............");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("ServletRequestListenerDemo Listener destruction...........");
    }
}
//Listening session listener
@WebListener
public class SessionListenerDemo  implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        System.out.println("SessionListenerDemo. . . establish session success");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("SessionListenerDemo. . . Destroy session");
    }

}

Then add the @ ServletComponentScan annotation on the startup class and it will be automatically registered in the container

ssionListenerDemo. . . Successfully created session "");
}

@Override
public void sessionDestroyed(HttpSessionEvent se) {
    System.out.println("SessionListenerDemo. . . Destroy session");
}

}

Then add @ServletComponentScan Annotations are automatically registered in the container



Deeper usage needs to be determined according to the business,Design by yourself



<center><font color=#Ff3366 size = 5 > like - collect - pay attention - easy to review and receive the latest content in the future < / font > < / center >

<center> <font color=#Ff3366 size = 4 > if you have other questions to discuss in the comment area - or send me a private letter - you will reply to < / font > < / center > as soon as you receive them

<center><font color=#Ff3366 size = 6 > in case of infringement, please contact me by private letter < / font > < / center >

<center> <font color=#Ff3366 size = 6 > thanks for your cooperation. I hope my efforts will help you ^ ^ ^ < / font > < / center >

Tags: Java Spring Boot filter

Posted on Tue, 21 Sep 2021 18:26:42 -0400 by cbcampbell