An overview of the

First, the interceptor in question is the SpringMVC interceptor, HandlerInterceptor. To use the SpringMVC interceptor, do the following:

  1. To create the interceptor class, you need to implement HandlerInterceptor
  2. Configure the interceptor in the XML configuration file with the following configuration code:
<mvc:interceptors> <mvc:interceptor> <! - / test/intercept * * this is the path to the test at the beginning of all urls - > < MVC: mapping path = "/ * *" / > <! -- This is the path that intercepts say exists --> <! - configure interceptor class path - > < bean class = "cn. LJK) for springmvc) controller. The MyInterceptor" > < / bean > <! < MVC: excide-mapping path="/fore/**"/> </ MVC :interceptor> </ MVC :interceptors>Copy the code

Since there are no XML files in SpringBoot, SpringBoot provides us with a Java Config way to configure the interceptor. There are two configuration modes:

  1. Inheriting WebMvcConfigurerAdapter (officially deprecated)
  2. Implement WebMvcConfigurer

Next start SpringBoot integration interceptor operation details!

Integrate interceptor combat operations

Step 1: Declare the interceptor class

This is done by implementing the HandlerInterceptor. The specific code is as follows:

public class LoginInterceptor implements HandlerInterceptor{}Copy the code

Step 2: Implement HandlerInterceptor with three interceptor methods

  • PreHandle: Intercepts Controller logic before it is executed
  • PostHandle: Controller logic completes but the view parser intercepts it before parsing
  • AfterCompletion: Intercepts the Controller logic and view parser after execution

In actual development, preHandle is frequently used, while postHandle and afterCompletion operations are relatively rare.

In the code below, the preHandle method is defined to intercept all access item urls and log information. Interception in postHandle before view parsing, via Model in the add data Request field.

AfterCompletion does not currently have any scenarios in mind, but if you have, you can comment on them in the comments section below.

The interceptor code is as follows:

public class LoginInterceptor implements HandlerInterceptor{ private Logger log = LoggerFactory.getLogger(LoginInterceptor.class); Public Boolean preHandle(HttpServletRequest Request, HttpServletResponse Response, Object handler) throws Exception { log.info("preHandle...." ); String uri = request.getRequestURI(); The info (" uri: "+ uri); if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; Log.info (" Intercepting Controller: "+ HandlerMethod.getBean ().getClass().getName()); Log.info (" Intercepting method: "+ handlermethod.getMethod ().getName()); } return true; } // Override public void postHandle(HttpServletRequest HttpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { log.info("postHandle...." ); Map<String,Object>map=modelAndView.getModel(); map.put("msg","postHandle add msg"); } @override public void afterCompletion(HttpServletRequest HttpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { log.info("afterCompletion...." ); }}Copy the code

Step 3: Configure the interceptor in Java Config mode

Inherits the WebMvcConfigurerAdapter mode

By inheriting WebMvcConfigurerAdapter and overriding the addInterceptors method, the interceptor is injected into the Spring context with its parameter, InterceptorRegistry.

Intercepting and non-intercepting paths are also set by InterceptorRegistry’s addPathPatterns and excludePathPatterns methods.

This is no longer recommended because the WebMvcConfigurerAdapter is marked as @deprecated.

@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {Copy the code

Inherit WebMvcConfigurerAdapter as follows:

@Configuration public class InterceptorConfigByExtendsWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter{ @Bean public LoginInterceptor loginInterceptor(){ return new LoginInterceptor(); } public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor()).addPathPatterns("/**").excludePathPatterns("/*.html"); }}Copy the code

The WebMvcConfigurer mode is implemented

By implementing the WebMvcConfigurer interface and implementing the addInterceptors method, you do the same as inheriting the WebMvcConfigurerAdapter. The specific code is as follows:

@Configuration public class InterceptorConfigByImplWebMvcConfigurer implements WebMvcConfigurer{ @Bean public LoginInterceptor loginInterceptor(){ return new LoginInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor()).addPathPatterns("/**").excludePathPatterns("/*.html"); }}Copy the code


test

Write ordinary Controller, the specific code is as follows:

@Controller public class IndexController { @GetMapping("/index") public String index(ModelAndView modelAndView){ return "index"; }}Copy the code

Create IndexController in the templates directory of SRC /main/resource to access the index.ftl page:

<h1>${msg}</h1>Copy the code

Since I’m using Freemarker as a page, I need to introduce the Freemarker starter dependency as follows:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>Copy the code

Localhost :8080/ sBE /index

Add data to MSG in Request field by Model before view parsing.

The output information is as follows: Interception address, interception Controller, and specific method

2019-09-24 15:53:04.144 INFO 7732 -- [niO-8080-exec-1] O.A.C.C.C. [Tomcat].[/sbe] : 2019-09-24 15:53:04.144 INFO 7732 -- [nio-8080-exec-1] O.A.C.C.C. [Tomcat].[/sbe] : Initializing Spring DispatcherServlet 'DispatcherServlet' 2019-09-24 15:53:04.145 INFO 7732 -- [NIO-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet' dispatcherServlet' 2019-09-24 15:53:04.153 INFO 7732 -- [NIO-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed Initialization in 8 ms 2019-09-24 15:53:04.155 INFO 7732 -- [NIO-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor : preHandle.... The 2019-09-24 15:53:04. 7732-155 the INFO [nio - 8080 - exec - 1] c.l ijunkui. Interceptor. LoginInterceptor: Uri: / sbe 15:53:04 index 2019-09-24. 7732-155 the INFO [nio - 8080 - exec - 1] c.l ijunkui. The interceptor. LoginInterceptor: Intercept Controller: Cn. Lijunkui. Controller. IndexController 15:53:04 2019-09-24. 7732-155 the INFO [nio - 8080 - exec - 1) c.lijunkui.interceptor.LoginInterceptor : Intercept method: index 15:53:04 2019-09-24. 7732-156 the INFO [nio - 8080 - exec - 1] c.l ijunkui. The interceptor. LoginInterceptor: postHandle.... The 2019-09-24 15:53:04. 7732-161 the INFO [nio - 8080 - exec - 1] c.l ijunkui. Interceptor. LoginInterceptor: afterCompletion...Copy the code

summary

The SpringBoot 2 integrator works much like the Filter integrator, injecting it into the Spring context through a registered class, The Filter uses the FilterRegistrationBean and the interceptor uses the InterceptorRegistry.

If you haven’t already used interceptors in SpringBoot projects, do so.

Code sample

See the code examples in my GitHub repository springbootexamples for a module named Spring-boot-2. x-interceptor

GitHub:https://github.com/zhuoqianmingyue/springbootexamples