Spring Boot interceptor
The previous article described the definitions of filters, which is also relatively simple. Filters belong to Servlet APIs and have nothing to do with Spring.
In Web development, we can use HandlerInterceptor provided by Spring in addition to filtering requests for web requests ).
HandlerInterceptor features similar to filters, but provides more refined control capabilities: before the request is responded, after the request is responded, before the view rendering, and after the request is all completed. We cannot use the Interceptor to modify the request content, but can throw an exception (or return false) to suspend request execution.
The interceptors implementing UserRoleAuthorizationInterceptor include:
ConversionServiceExposingInterceptor
CorsInterceptor
LocaleChangeInterceptor
PathExposingHandlerInterceptor
ResourceUrlProviderExposingInterceptor
ThemeChangeInterceptor
UriTemplateVariablesHandlerInterceptor
UserRoleAuthorizationInterceptor
LocaleChangeInterceptor and ThemeChangeInterceptor are commonly used.
Configuring the interceptor is also very simple. Why does Spring provide the basic class webmvcjavaseradapter? We only need to override the addInterceptors method to add the register interceptor.
Three steps are required to implement the custom Interceptor:
1. create our own interceptor class and implement the HandlerInterceptor interface.
2. Create a Java class that inherits webmvcjavaseradapter and override the addInterceptors method.
2. instantiate our custom interceptor and manually add the object to the interceptor chain (added in the addInterceptors method ).
PS: This article focuses on how to use interceptor in Spring-Boot. For more information about the principle of interceptor, see.
Sample Code:
MyInterceptor1.java
Package org. springboot. sample. interceptor; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. springframework. web. servlet. handlerInterceptor; import org. springframework. web. servlet. modelAndView;/*** custom interceptor 1 *** @ author single Hongyu (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create January 7, 2016 */public class MyInterceptor1 implements HandlerInterceptor {@ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System. out. println (">>> MyInterceptor1 >>>>>>> call before request processing (before calling the Controller Method)"); return true; // The execution continues only when true is returned. If false is returned, the current request is canceled.} @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System. out. println (">>> MyInterceptor1 >>>>>>> call after request processing, but before the view is rendered (after the Controller method is called )");} @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System. out. println (">>> MyInterceptor1 >>>>>>> called after the end of the entire request, that is, execute after DispatcherServlet renders the corresponding view (mainly used for resource cleaning )");}}
MyInterceptor2.java
Package org. springboot. sample. interceptor; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import org. springframework. web. servlet. handlerInterceptor; import org. springframework. web. servlet. modelAndView;/*** custom interceptor 2 *** @ author single Hongyu (365384722) * @ myblog http://blog.csdn.net/catoop/ * @ create January 7, 2016 */public class MyInterceptor2 implements HandlerInterceptor {@ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System. out. println (">>> MyInterceptor2 >>>>>>> call before request processing (before calling the Controller Method)"); return true; // The execution continues only when true is returned. If false is returned, the current request is canceled.} @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System. out. println (">>> MyInterceptor2 >>>>>>> call after request processing, but before the view is rendered (after the Controller method is called )");} @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System. out. println (">>> MyInterceptor2 >>>>>>> called after the end of the entire request, that is, execute after DispatcherServlet renders the corresponding view (mainly used for resource cleaning )");}}
MyWebAppConfigurer. java
Package org. springboot. sample. config; import org. springboot. sample. interceptor. myInterceptor1; import org. springboot. sample. interceptor. myInterceptor2; import org. springframework. context. annotation. configuration; import org. springframework. web. servlet. config. annotation. interceptorRegistry; import org. springframework. web. servlet. config. annotation. webMvcConfigurerAdapter; @ Configurationpublic class MyWebAppConfigurer extends WebMvcConfigurerAdapter {@ Override public void addInterceptors (InterceptorRegistry registry) {// multiple interceptors form an interceptor chain // addPathPatterns is used to add interception rules // excludePathPatterns users exclude interception registry. addInterceptor (new MyInterceptor1 ()). addPathPatterns ("/**"); registry. addInterceptor (new MyInterceptor2 ()). addPathPatterns ("/**"); super. addInterceptors (registry );}}
After entering the address http: // localhost: 8080/index in the browser, the console output is:
>>> MyInterceptor1 >>>>>> call before request processing (before calling the Controller Method) >>> myInterceptor2 >>>>>> call before request processing (before calling the Controller Method) >>> MyInterceptor2 >>>>>> call after request processing, but before the view is rendered (after the Controller method is called) >>>> MyInterceptor1 >>>>>> call after request processing, however, before the view is rendered (after the Controller method is called) >>>> MyInterceptor2 >>>>>> is called after the request is complete, that is, after DispatcherServlet renders the corresponding view, it is executed (mainly used for resource cleaning) >>> MyInterceptor1 >>>>>> called after the end of the entire request, that is, after DispatcherServlet renders the corresponding view, it is executed (mainly used for resource cleaning)
According to the output, you can understand the execution sequence of the interceptor chain (For details, refer to du Niang)
The last point is to emphasize that only requests that pass through the DispatcherServlet will go through the interceptor chain. Our custom Servlet requests will not be intercepted, for example, our custom Servlet address http: // localhost: 8080/xs/myservlet will not be intercepted by the interceptor. And no matter which Servlet it belongs, the filter will intercept as long as the filtering rules of the composite filter.
Finally, the webmvcjavaseradapter we used above is not just used to register and add an interceptor. As its name suggests, it is used for Web configuration. It can also have many other functions. You can get a rough idea below, what is the use of each method, and leave it to everyone for their own research (in fact, it is very easy to look at the same way ).