Spring Boot's simple tutorial interceptors, filters, listeners

Many times we want to do something unrelated to business logic, such as counting the number of people online, screening login accounts, counting page views and so on. At this point we need to use the tools mentioned today.

  1. First let's look at the interceptor.
    We need to customize an interceptor and write our own logic processing.

    @Slf4j
    public class MyInterceptor implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            log.info("preHandle:Call before request");
            //Returning false requests interruption
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                               ModelAndView modelAndView) throws Exception {
            log.info("postHandle:Call after request");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception {
            log.info("afterCompletion:Callback method after request completion, that is, callback after view rendering is completed");
        }
    }

    Then we need to register the interceptor.

    public class WebMvcConfigurer extends WebMvcConfigurationSupport {
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            //Registered Interceptor Interception Rules
            //When multiple interceptors are added in this order of execution, in the order of addition
            registry.addInterceptor(getHandlerInterceptor()).addPathPatterns("/*");
        }
    
        @Bean
        public static HandlerInterceptor getHandlerInterceptor() {
            return new MyInterceptor();
        }
    }

    Of course, you need to add the annotation @ServletComponentScan to the startup class to take effect. This is a simple and logical interceptor. If you need any special operation, you can write it directly in our customized interceptor method.

  2. Next, let me take a look at the filter. Like the interceptor above, we need to customize a filter to implement the method we want to achieve.

    @Slf4j
    public class MyFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            log.info("filter Initialization");
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            // TODO Auto-generated method stub
            log.info("doFilter Request processing");
            //Pretreatment of request and response
            // For example, set the request code
            // request.setCharacterEncoding("UTF-8");
            // response.setCharacterEncoding("UTF-8");
            //TODO Business Logic
    
            //Links are passed directly to the next filter
            chain.doFilter(request, response);
        }
    
        @Override
        public void destroy() {
            log.info("filter Destruction");
        }
    }

    Then we call the filter we wrote.

    @Configuration
    public class FilterConfig {
        @Bean
        public FilterRegistrationBean ResistFilter() {
            FilterRegistrationBean registration = new FilterRegistrationBean();
            //When the filter has injected other bean classes, the entity class filter can be implemented directly through @bean, so that other bean classes used by the filter can not be injected automatically.
            //Of course, if no other bean s need to be retrieved, you can either use new MyFilter() directly or getBean.
            registration.setFilter(new MyFilter());
            //Filter name
            registration.setName("customFilter");
            //Interception Path
            registration.addUrlPatterns("/hello");
            //Setting order
            registration.setOrder(10);
            return registration;
        }
    }

    Where in the interceptor we have added annotations to the startup class, so there is no need to add them again.

  3. Let's finally look at the listener, where the listener does not need to call and other operations, just write well, add comments on it.

    /**
     * Monitor
     * SerletRequestListener generally implements web browsing
 */
@WebListener
@Slf4j
public class ServletLister implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        log.info("Monitor: Destruction");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        log.info("Listener: Initialization");
    }
}
```
```
/**
 * Monitor
 * httpSessionListener To Realize the Statistics of Online Number
 * @author zhouzhaodong
 */
@WebListener
@Slf4j
public class HttpLister implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        log.info("Someone is online again. Let's count the number of people online.");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        log.info("Someone is offline again. Let's count the number of people online.");
    }
}
```
//The listener is mainly used to count the number.
//That is to simply record the simple use of interceptors, filters and monitors, and then update this article if there are detailed use methods in the future.
//Code download address: https://github.com/zhouzhaodong/Study

Keywords: Java github

Added by David Rech on Tue, 30 Jul 2019 07:05:47 +0300