Springboot

1: Interceptor

Interceptors in Java are objects that dynamically intercept action calls. Rely on the Web framework, in springMVC rely on springMVC framework, in the implementation of java-based reflection mechanism, belongs to an APPLICATION of AOP, the role is similar to the filter, but the interceptor can only intercept the Controller request, the other direct access to static resources request cannot intercept processing.

Interceptors can intercept front-end requests. To define the interceptor, you need to implement the HandlerInterceptor interface, and then rewrite the preHandle, postHandle, and afterCompletion methods as required.

/** * interceptor **@program: myspringboot
 * @author: syt
 * @create: 2020-03-05 21:11
 */
@Component
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("Front interceptor ****");
        // Return true to indicate that the request was passed and false to indicate that the request was intercepted
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("Rear interceptor ****");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("Interceptor execution completed ****"); }}Copy the code

To make your interceptor work, you need to configure webMVC. A custom configuration class implements the WebMvcConfigurer interface. The addInterceptors method is then overridden to add the path to intercept. JDK1.8 inherits the WebMvcConfigurerAdapter and re-sets the method. However,JDK1.8 supports the interface default method. We can implement WebMvcConfigurer without inheritingWebMvCConfigurerAdapter.

Configure interceptors and filters@program: myspringboot
 * @author: syt
 * @create: 2020-03-05 21:16* /@Configuration
public class MyConfig implements WebMvcConfigurer {
    @Autowired
    private MyInterceptor myInterceptor;
    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        Addpa-thpatterns is used to add interception rules
        ExcludePathPatterns is used to rule out intercepts
        /* The interceptor to execute */
        registry.addInterceptor(myInterceptor).
                addPathPatterns("/ * *").
                excludePathPatterns("/**/login"."/**/esProductinfo/**");
    }

    Origin is the protocol, domain name, and port number. * A URL consists of a protocol, domain name, port, and path. If two urls have the same protocol, domain name, and port, * indicates that they are of the same origin. Otherwise, if any protocol, domain name, or port is different, it is cross-domain * *@param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/ *")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET"."POST"."DELETE"."PUT"."PATCH")
                .maxAge(3600); }}Copy the code

The custom configuration class can inherit WebMvcConfigurationSupport class. This class has a lot of the default configuration, but if this class is inherited WebMvcConfigurationSupport, SpringBoot MVC automatic assembly good failure, default configuration needs to be their own definition, For example, static file address /**, you need to re-addResourceHandlers method to add static file address

/** * Configure interceptors and filters **@program: myspringboot
 * @author: syt
 * @create: 2020-03-05 21:16
 */
@Configuration
public class MyConfig extends WebMvcConfigurationSupport {
    @Autowired
    private MyInterceptor myInterceptor;

      /** * Static resource **@param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/META-INF/resources/static/");
    }

    /**
     * 添加拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        Addpa-thpatterns is used to add interception rules
        ExcludePathPatterns is used to rule out intercepts
        /* The interceptor to execute */
        registry.addInterceptor(myInterceptor).
                addPathPatterns("/ * *").
                excludePathPatterns("/**/login"."/**/esProductinfo/**");
    }

    Origin is the protocol, domain name, and port number. * A URL consists of a protocol, domain name, port, and path. If two urls have the same protocol, domain name, and port, * indicates that they are of the same origin. Otherwise, if any protocol, domain name, or port is different, it is cross-domain * *@param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/ *")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET"."POST"."DELETE"."PUT"."PATCH")
                .maxAge(3600); }}Copy the code

2: Filter

Methods a

Filters and intercepts requests and responses to target resources. Before the request reaches the servlet, a logical judgment is made to determine whether the request is allowed to the servlet. You can also filter a response before it reaches the client to determine whether it is allowed to return to the client.

To define a Filter, you need to implement the Filter interface

@Slf4j
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("MyFilter init method");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("DoFilter method for MyFilter");
        // We can add a judgment here to return our own information if the filter request fails
        if (false) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        } else {
            servletResponse.setContentType("text/html; charset=UTF-8;");
            PrintWriter out = servletResponse.getWriter();
            out.write("Filter does not pass");
            log.info("Filter does not pass");
            out.flush();
            out.close();
            return; }}@Override
    public void destroy(a) {
        log.info("MyFilter destroy method"); }}Copy the code

To make filters work, you need to configure them

@Configuration
public class MyConfig{
  
    /** * add filter **@return* /
    @Bean
    public FilterRegistrationBean filterRegistrationBean(a) {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());
        // The default value is false, meaning that the lifecycle is managed by SpringApplicationContext, or true, meaning that it is managed by ServletContainer
        registration.addInitParameter("targetFilterLifecycle"."true");
        registration.setEnabled(true);
        // Filter is executed in the order of a smaller number
        registration.setOrder(1);
        // The url path to intercept
        registration.addUrlPatterns("/demand/*"."/notice/*"."/query/*");
        returnregistration; }}Copy the code

Way 2

You can create filters directly with the @WebFilter annotation and the @Component annotation

@Slf4j
@Component
@WebFilter(filterName = "myFilter",urlPatterns = "/ *")
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("MyFilter init method");
    }

    /** * here is the method for filtering requests */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("DoFilter method for MyFilter");
        if (false) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        } else {
            servletResponse.setContentType("text/html; charset=UTF-8;");
            PrintWriter out = servletResponse.getWriter();
            out.write("Filter does not pass");
            log.info("Filter does not pass");
            out.flush();
            out.close();
            return; }}@Override
    public void destroy(a) {
        log.info("MyFilter destroy method"); }}Copy the code

Feel like interceptors and filters can intercept requests and process them accordingly. Let’s talk about the specific differences.

Interceptors are Java-based reflection mechanisms, while filters are based on function callbacks. ② filters depend on the servlet container, and interceptors do not. ③ Interceptors only work on action requests, while filters work on almost all requests. (4) Interceptors can access action context, value stack objects, but filters cannot. ⑤ : Interceptors can be called multiple times during the life of an action, while filters can only be called once when the container is initialized. (6) The interceptor can fetch individual beans from the IOC container, while the filter cannot. (Inject a service into the interceptor to invoke business logic.) ⑦ Filters are preprocessed after the request enters the container, but before it enters the servlert. Responding to a request is also triggered after the servlet has finished processing and before it is returned to the client. The interceptor supports three methods: (1) preHandle: a preprocessing callback method that implements processor preprocessing (e.g., login check), and a third argument that takes the responding processor (e.g., Controller implementation in the previous chapter); Return value: true to continue the process (such as calling the next interceptor or processor); False indicates that the process is interrupted (such as failed login check) and will not continue to call other interceptors or processors. In this case, we need to generate a response through response. PostHandle: post-processing callback method that implements post-processing by the processor (but before rendering the view), at which point we can process model data or view through modelAndView (modelAndView objects), which may also be null. AfterCompletion: A callback method is used when the view is rendered. For example, in performance monitoring, we can record the end time and output the elapsed time. We can also do some resource cleaning, similar to finally in try-catch-finally. But only afterCompletion is called for the interceptor in the handler execution chain where preHandle returns true.

Code cloud address: gitee.com/sytsuccess/…

Reference links: blog.csdn.net/u013806366/…