[Springboot] filter, listener, interceptors, Aspect sliced

Editor:

  https://blog.csdn.net/cp026la/article/details/86501019

Summary:

  This chapter describes the interceptors, filters, using a simple slicing using the difference between the intercepted request, and the listener springboot1.5

Filter, interceptor contrast, intercepts the request of a slice:

The same point: can intercept the request.
Different points:
1, the filter of intercepting only request information acquired in the original Request and Response.
2, the interceptor to intercept the request can obtain the original Request, Response, and all of the controller and method names, but the information is not obtainable method.
3, Aspect slice can only get the parameters of the method, the original Request, Response can not get.

Therefore, the actual project needs to be selected according to the manner in which the use of intercept request.

A filter:

1, to achieve Filter interface

/**
 * @Auther: xf
 * @Date: 2018/11/19 19:30
 * @Description: Custom filter
 *
 * Filter only get request and response do not know which controller processes the request
 */
@ Slf4j
public class CustomFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info ( "Filter Initialization >>>>>>>");
    }

    /**
     * When a request is intercepted call
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info ( ">>>>>>>>>>>> filter intercepts the request processing logic >>>>>>>>>>>>>");

        // Business logic
        long startTime = System.currentTimeMillis();

        // filter chain to the next filter
        filterChain.doFilter(servletRequest, servletResponse);
        log.info ( "request time:" + (System.currentTimeMillis () - startTime));
    }

    @Override
    public void destroy() {
        log.info ( "Destruction >>>>>>> Filter");
    }
}  

 

2, the filter configuration class:

Traditional web project, the filter configuration is added in web.xml. SpringBoot FilterRegistrationBean need to complete the configuration.

/**
 * @Auther: xf
 * @Date: 2018/11/19 19:58
 * @Description: traditional project configuration Filter added in web.xml
 * In Spring boot, we need to complete the configuration FilterRegistrationBean
 */
@Configuration
public class CustomFilterConfig {
    @Bean
    public FilterRegistrationBean customFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new CustomFilter());
        registration.addUrlPatterns("/*");
        registration.setName("customFilter");
        registration.setOrder(1);
        return registration;
    }
}  


3, start the project, just request an interface test results:

There interceptor console log.

4, the filter configuration of two ways:

Direct configuration (configuration type commented above CustomFilterConfig) annotation by @WebFilter

@ Slf4j
// plurality of filters, with this annotation to specify the execution order, the smaller the first execution
@Order(1)
// Configure commented @WebFilter in the CustomFilterConfig
@WebFilter(urlPatterns = "/*", filterName = "customFilter")
public class CustomFilter implements Filter {
    ...
}  

Note:
@WebFilter is Servlet3.0 the norm, not the SpringBoot provided, plus the need to scan the specified package @ServletComponentScan comment. Here we added to the startup class.

// filter and servlet, like the listener needs to register in order to use a separate, spring boot which provides the annotation to play the role of registration
@ServletComponentScan
// mapper scan package configuration interface class
@MapperScan("com.coolron.*.dao")
@SpringBootApplication(scanBasePackages = "com.coolron")
public class SpringbootApplication {
    ...
}  


Second, the interceptor:

1, custom interceptor 1:

@ Slf4j
public class MyInterceptor1 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  throws Exception {
        log.info ( ">>> MyInterceptor1 >>>>>>> call (Controller prior method call) before the request processing");
        return true; // returns true only will continue down, return false to cancel the current request
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        ( "After the call request >>> MyInterceptor1 >>>>>>> after treatment, but before the view is rendered (Controller method call)") log.info;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        log.info ( ">>> MyInterceptor1 >>>>>>> is called after the end of the entire request, that is DispatcherServlet rendering the corresponding view after performing (mainly used for resource cleanup)");
    }
}  

2, custom interceptor 2:

/**
 * Custom interceptors 2
 */
@ Slf4j
public class MyInterceptor2 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        log.info ( ">>> MyInterceptor2 >>>>>>> call (Controller prior method call) before the request processing");
        return true; // returns true only will continue down, return false to cancel the current request
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        ( "After the call request >>> MyInterceptor2 >>>>>>> after treatment, but (Controller method called before the view is rendered)") log.info;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        log.info ( ">>> MyInterceptor2 >>>>>>> is called after the end of the entire request, that is DispatcherServlet rendering the corresponding view after performing (mainly used for resource cleanup)");
    }
}

3, the interceptor configuration class:

/**
 * @Auther: xf
 * @Date: 2018/11/19 21:09
 * @Description:
 */
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    /*
     * Interceptor configuration
     * Add the spring-mvc.xml profile <mvc: interceptor> tag arranged interceptor.
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        A plurality of interceptors // interceptor chain
        // addPathPatterns to add blocking rules
        // excludePathPatterns user to exclude interception
         registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/**").excludePathPatterns("/login");
         registry.addInterceptor(new MyInterceptor2()).addPathPatterns("/**");
        // parent class configuration
        super.addInterceptors(registry);
    }
}  

Three, Aspect slice interception:

1, custom slice:

/**
 * @Description:  
 * Specific parameter values ​​can get request process corresponding to the particular controller, but can not get the original request and response
 *
 * Entry point (notes):
 * 1, work on which method
 * 2, when works
 *
 * Enhanced (method)
 * 1, business logic function is executed
 */
// class declaration sliced
@ Slf4j
@Aspect
@Component
public class CustomAspect {

    // at what time works
    // @Before () equivalent interceptors PreHandle () method
    // @After () method intercepted response after execution
    // @AfterThrowing method throws an exception when some call
    // @Around cover surrounds the first three
    // invoke surrounded by the following method
    @Around("execution(* com.coolron.*.controller..*.*(..))")
    // ProceedingJoinPoint class contains methods currently interception of some information
    public Object method(ProceedingJoinPoint pjp) throws Throwable {
        log.info ( "===== Aspect ======= process");
        Object[] args = pjp.getArgs();
        for (Object arg : args) {
            log.info ( "parameters are:" + arg);
        }
        long start = System.currentTimeMillis();
        // equivalent of chain.doFilter Filter () method call that returns the object to be intercepted in the controller method returns the value of the same value
        Object object = pjp.proceed();
        log.info("Aspect 耗时:" + (System.currentTimeMillis() - start));
        return object;
    }
}  

 

execution expression See SpringBoot> 07 - transaction processing.

2, start Access any interface:

Watch the console found Filter, Interceptor, slicing the order of execution:

Interception sequence: Filter >>> Interceptor >>> Aspect >>> controller
Ruoguo abnormal return results: controller >>> Aspect >>> ControllerAdvice (based on the global exception handler) >>> Interceptor >>> Filter

Fourth, the listener:

1, custom listener, implement the interface ServletRequestListener

/**
 * @Auther: xf
 * @Date: 2018/11/19 21:42
 * @Description: Listener
 */
@ Slf4j
@WebListener
public class RequestListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        log.info ( "listener destroy >>>>>");
    }

    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        log.info ( "listener initialization >>>>>");
    }
} 

 

2, the test: request a casual listener interface to see the log initialization and destruction.

Note: Case is implemented request of listeners. Listening request object used to create and destroy.
Common listener:
1, HttpSessionListener: listening session object to create, destroy
2, ServletRequestListener: create a listener request objects, destroy
3, ServletContextListener: servletContext create a listener object destruction

Guess you like

Origin www.cnblogs.com/wjqhuaxia/p/12148842.html