Play SpringBoot 2 Fast Integration Interceptor

Summary

First of all, the interceptor mentioned here is the interceptor HandlerInterceptor of spring MVC. Using Spring MVC interceptor requires the following actions:

  1. Creating interceptor classes requires the implementation of Handler Interceptor
  2. Configure the interceptor in the xml configuration file. The specific configuration code is as follows:
<mvc:interceptors>
    <mvc:interceptor>
    <! - / test /** This is all the URLs that the interception path starts with / test - >.
    <mvc: mapping path="/**"/><! --- This is the path of interception - >"
    <! - Configure the interceptor class path - >
    <bean class="cn.ljk.springmvc.controller.MyInterceptor"></bean>
    <! - Configure the non-interceptor URL path - >
    <mvc:exclude-mapping path="/fore/**"/>
    </mvc:interceptor>
</mvc:interceptors>

Because there are no xml files in SpringBoot, SpringBoot provides us with a Java Config way to configure interceptors. There are two configurations:

  1. Inheritance of WebMvc Configurer Adapter (official no longer recommended)
  2. Implementing WebMvcConfigurer

Next, the SpringBoot integrated interceptor operation is introduced in detail!

Integrated Interceptor Operations

Step 1: Declare the interceptor class

By implementing Handler Interceptor. The code is as follows:

public class LoginInterceptor implements HandlerInterceptor{}

Step 2: Implementing three interception methods for Handler Interceptor

  • preHandle: Intercept before Controller logic executes
  • PosHandle: The Controller logic is executed, but the view parser intercepts it before parsing.
  • After Completion: Controller logic and view parser are executed to intercept

In actual development, preHandle is used more frequently than postHandle and afterCompletion.

In the following code, the preHandle method defines intercepting all access project URL s and logging information. The postHandle intercepts the view before parsing, and adds the data Request field through the Model.

After Completion has not thought of using scenarios for the time being. If you have used scenarios, you can comment in the comments section below.

The interceptor code is as follows:

public class LoginInterceptor implements HandlerInterceptor{
    
    private Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
    
    //Prior to the execution of Controller Controller logic
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle....");
        String uri = request.getRequestURI();
        log.info("uri: "+ uri);
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            log.info("intercept Controller: "+ handlerMethod.getBean().getClass().getName());
            log.info("Interception methods:"+handlerMethod.getMethod().getName());
        }
        
        return true;
    }
    
    //The Controller logic is executed, but the view parser is before parsing.
    @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");
    }
    
    //Controller Logic and View Parser Executed
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("afterCompletion....");
    }
}

Step 3: Java Config way to configure interceptors

Inheritance of WebMvc Configurer Adapter

By inheriting WebMvcConfigurerAdapter and overwriting the addInterceptors method, the interceptor is injected into Spring's context through its parameter InterceptorRegistry.

Interceptor Registry's addPathPatterns and excludePathPatterns methods set up interception paths and non-interception paths.

This approach is no longer recommended by the authorities because they have marked WebMvc Configurer Adapter as @Deprecated.

@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {

The code for inheriting WebMvc Configurer Adapter is 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");
        }
}

Implementing WebMvc Configurer

By implementing the WebMvcConfigurer interface and implementing the addInterceptors method, other operations are the same as inheriting the WebMvcConfigurer Adapter. The code is as follows:

```java
@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");
    }
}
```

test

Write the general Controller, the specific code is as follows:

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

Create IndexController access page index.ftl in the templates directory under src/main/resource. The code is as follows:

<h1>${msg}</h1>

Because I use Freemarker here when I use the page, I say that I need to introduce Freemarker starter dependency. The specific points are as follows:

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

Visit localhost:8080/sbe/index through the visitor. The specific effects are as follows:

As shown in the figure above, msg is successfully displayed by adding data to Request domain through Model before view parsing.

Log output information is as follows: intercept address and intercept Controller and specific methods for log output

2019-09-24 15:53:04.144  INFO 7732 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/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....
2019-09-24 15:53:04.155  INFO 7732 --- [nio-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor  : uri: /sbe/index
2019-09-24 15:53:04.155  INFO 7732 --- [nio-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor  : intercept Controller: cn.lijunkui.controller.IndexController
2019-09-24 15:53:04.155  INFO 7732 --- [nio-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor  : Interception methods: index
2019-09-24 15:53:04.156  INFO 7732 --- [nio-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor  : postHandle....
2019-09-24 15:53:04.161  INFO 7732 --- [nio-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor  : afterCompletion....

Summary

SpringBoot 2 integrates an interceptor and an integrator Filter, which are injected into Spring's context through a registered class, except that the Filter uses a FilterRegistration Bean and the interceptor uses an Interceptor Registry.

I think it's simpler than using xml configuration. If you haven't used the interceptor in the spring boot project, please operate it quickly!

Code example

Examples of specific code can be seen in the spring boot text amples module named spring-boot-2.x-interceptor project in my GitHub repository

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

Tags: Java Spring SpringBoot xml

Posted on Mon, 07 Oct 2019 13:34:37 -0400 by bucko