Fun SpringBoot 2 rapid integration interceptor

Outline

First statement about here is SpringMVC interceptor interceptor HandlerInterceptor. Use SpringMVC interceptor needs to do the following:

  1. Creating interceptor class needs to implement HandlerInterceptor
  2. The interceptor arranged in the xml configuration file, the specific configuration code is as follows:
<mvc:interceptors>
    <mvc:interceptor>
    <!-- /test/** 这个是拦截路径以/test开头的所有的URL-->
    <mvc:mapping path="/**"/><!—这个是拦截说有的路径-->
    <!-- 配置拦截器类路径-->
    <bean class="cn.ljk.springmvc.controller.MyInterceptor"></bean>
    <!-- 配置不拦截器URL路径-->
    <mvc:exclude-mapping path="/fore/**"/>
    </mvc:interceptor>
</mvc:interceptors>

Because there is no xml file in SpringBoot, the so SpringBoot provides us with Java Config way to configure interceptors. There are two configurations:

  1. Inheritance WebMvcConfigurerAdapter (officials have not recommended)
  2. Achieve WebMvcConfigurer

Then start SpringBoot integrated interceptor operating details!

Integrated interceptor combat operations

The first step: Declare interceptor class

It is accomplished by implementing HandlerInterceptor. Specific code as follows:

public class LoginInterceptor implements HandlerInterceptor{}

Step Two: Implement HandlerInterceptor 3 interceptors method

  • preHandle: Controller logic is executed before intercepting
  • postHandle: Controller logic is finished but also to intercept view resolver to be resolved before
  • afterCompletion: Controller logic is finished and intercept ViewRenderer

Actual development preHandle relatively high frequency, postHandle afterCompletion and relatively few operations.

Defined in the following code preHandle method of blocking all access to the project URL and log records. postHandle intercept the front view resolution, adding Request domain data passes Model.

afterCompletion temporarily did not expect usage scenarios, if you have used scenes can comment in the comments section below.

Detailed interceptor code is as follows:

public class LoginInterceptor implements HandlerInterceptor{
    
    private Logger log = LoggerFactory.getLogger(LoginInterceptor.class);
    
    //ControllerController逻辑执行之前
    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("拦截 Controller:"+ handlerMethod.getBean().getClass().getName());
            log.info("拦截方法:"+handlerMethod.getMethod().getName());
        }
        
        return true;
    }
    
    //Controller逻辑执行完毕但是视图解析器还为进行解析之前
    @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逻辑和视图解析器执行完毕
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("afterCompletion....");
    }
}

The third step: Java Config way to configure interceptors

Inheritance WebMvcConfigurerAdapter way

And by override inherited WebMvcConfigurerAdapter addInterceptors method by which the interceptor parameter InterceptorRegistry Spring injected into the context.

Further intercepting the path and does not intercept the path set by the InterceptorRegistry addPathPatterns and excludePathPatterns method.

In this way officials have not recommended, because the official has been marked as @Deprecated the WebMvcConfigurerAdapter.

@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {

DETAILED succession WebMvcConfigurerAdapter code 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");
        }
}

Way to achieve WebMvcConfigurer

WebMvcConfigurer by implementing the interface and achieve addInterceptors way as other operations and inheritance WebMvcConfigurerAdapter way. Specific code 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 generic Controller, specific code as follows:

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

Creating IndexController access page index.ftl in the templates directory under src / main / resource, the following code:

<h1>${msg}</h1>

Since I used here is Freemarker when the page used to say that the need to introduce Freemarker starter dependent on the specific points are as follows:

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

Tour by accessing localhost: 8080 / sbe / index, to access specific effects as follows:

Here Insert Picture Description

As shown in FIG Model times by adding data to the domain Request msg successfully resolve a front view of the displayed!

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

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  : 拦截 Controller:cn.lijunkui.controller.IndexController
2019-09-24 15:53:04.155  INFO 7732 --- [nio-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor  : 拦截方法: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 integration operation interceptors like Filter and integration, is registered by a class which is injected into the context of Spring, but using FilterRegistrationBean Filter and interceptors are used InterceptorRegistry.

Personally I feel that way than using xml configuration easier, and if you have not used in SpringBoot interceptor project, make haste to operate about it!

The sample code

Specific code example in my GitHub repository springbootexamples in module called spring-boot-2.x-interceptor project view

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

Guess you like

Origin www.cnblogs.com/jerry126/p/11621350.html