Spring Boot interceptor HandlerInterceptor (transfer)

The previous article explained the definition of the filter, which is also relatively simple. The filter belongs to the API of the Servlet category and has nothing to do with spring .     In web development, in addition to using  Filter  to filter web requests, we can also use the HandlerInterceptor (interceptor) provided by Spring .  

HandlerInterceptor  functions similar to filters, but provides more fine-grained control: before the request is responded to, after the request is responded, before the view is rendered, and after the request is complete. We cannot modify the content of the request through interceptors , but we can suspend the execution of the request by throwing an exception (or returning false ).

The interceptors that implement  UserRoleAuthorizationInterceptor  are: ConversionServiceExposingInterceptor CorsInterceptor LocaleChangeInterceptor PathExposingHandlerInterceptor ResourceUrlProviderExposingInterceptor ThemeChangeInterceptor UriTemplateVariablesHandlerInterceptor UserRoleAuthorizationInterceptor 
 
 
 
 
 
 
 

Among them,  LocaleChangeInterceptor  and  ThemeChangeInterceptor are  more commonly used.

Configuring interceptors is also very simple. Why does Spring  provide the basic class WebMvcConfigurerAdapter  , we only need to rewrite the addInterceptors  method to add registered interceptors.

Implementing a custom interceptor only requires 3 steps: 1. Create our own interceptor class and implement the  HandlerInterceptor  interface. 2. Create a Java class that inherits WebMvcConfigurerAdapter and override  the addInterceptors  method. 2. Instantiate our custom interceptor, and then manually add the object to the interceptor chain (add it in the addInterceptors method). PS : This article focuses on how to use interceptors in Spring-Boot . Please refer to the information for the principle of interceptors. 
 
 
 

Code example:

com.kfit.interceptor.MyInterceptor1.java

package com.kfit.interceptor;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

 

/**

 * 自定义拦截器1

 *

 * @author   Angel

 */

publicclassMyInterceptor1implementsHandlerInterceptor {

 

    @Override

    publicboolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

            throws Exception {

        System.out.println(">>>MyInterceptor1>>>>>>>在请求处理之前进行调用(Controller方法调用之前)");

 

        returntrue;// 只有返回true才会继续向下执行,返回false取消当前请求

    }

 

    @Override

    publicvoid postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,

            ModelAndView modelAndView) throws Exception {

        System.out.println(">>>MyInterceptor1>>>>>>>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");

    }

 

    @Override

    publicvoid afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)

            throws Exception {

        System.out.println(">>>MyInterceptor1>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");

    }

 

}

 

com.kfit.interceptor.MyInterceptor2.java

package com.kfit.interceptor;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

 

/**

 * 自定义拦截器2

 *

 * @author   Angel

 */

publicclassMyInterceptor2implementsHandlerInterceptor {

 

    @Override

    publicboolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

            throws Exception {

        System.out.println(">>>MyInterceptor2>>>>>>>在请求处理之前进行调用(Controller方法调用之前)");

 

        returntrue;// 只有返回true才会继续向下执行,返回false取消当前请求

    }

 

    @Override

    publicvoid postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,

            ModelAndView modelAndView) throws Exception {

        System.out.println(">>>MyInterceptor2>>>>>>>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");

    }

 

    @Override

    publicvoid afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)

            throws Exception {

        System.out.println(">>>MyInterceptor2>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");

    }

 

}

 

Com.kfit.config.MyWebAppConfigurer.java

package com.kfit.config;

 

import com.kfit.interceptor.MyInterceptor1;

import com.kfit.interceptor.MyInterceptor2;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

 

@Configuration

publicclassMyWebAppConfigurer

        extendsWebMvcConfigurerAdapter {

 

    @Override

    publicvoid addInterceptors(InterceptorRegistry registry) {

        // 多个拦截器组成一个拦截器链

        // addPathPatterns 用于添加拦截规则

        // excludePathPatterns 用户排除拦截

        registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/**");

        registry.addInterceptor(new MyInterceptor2()).addPathPatterns("/**");

        super.addInterceptors(registry);

    }

 

}

 

然后在浏览器输入地址: http://localhost:8080/index 后,控制台的输出为:

>>>MyInterceptor1>>>>>>>在请求处理之前进行调用(Controller方法调用之前)

>>>MyInterceptor2>>>>>>>在请求处理之前进行调用(Controller方法调用之前)

>>>MyInterceptor2>>>>>>>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)

>>>MyInterceptor1>>>>>>>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)

>>>MyInterceptor2>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)

>>>MyInterceptor1>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)

 

根据输出可以了解拦截器链的执行顺序(具体原理介绍,大家找度娘一问便知)

最后强调一点:只有经过DispatcherServlet 的请求,才会走拦截器链,我们自定义的Servlet 请求是不会被拦截的,比如我们自定义的Servlet地址http://localhost:8080/myServlet1 是不会被拦截器拦截的。并且不管是属于哪个Servlet 只要复合过滤器的过滤规则,过滤器都会拦截。

Finally, the  WebMvcConfigurerAdapter  we used above is not just for registering and adding interceptors. As the name suggests, it is used for Web configuration. It can also have many other functions. You can get a general understanding of what each method does through the screenshots below. It is used, and I leave it to everyone to study for themselves (in fact, they are all similar and very simple).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326946175&siteId=291194637