本文主要是介绍SpringBoot高版本添加拦截器,替代WebMvcConfigurerAdapter,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一.创建类实现HandlerInterceptor接口,重写接口中的三个方法
@Component注解,方便后面使用时进行注入
@Slf4j注解,简化log写法,添加lombok依赖后可以使用
package com.datang.demo;import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@Slf4j
@Component
public class InterceptorConfig implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception{log.info("自定义拦截器");return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView modelAndView){log.info("处理请求完成后视图渲染之前的处理操作");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e) throws Exception {log.info("视图渲染之后的操作");}}
二.spring boot 2.0、Spring 5.0 以后WebMvcConfigurerAdapter会取消掉,新的版本解决方案目前有两种:
1) 创建类继承WebMvcConfigurationSupport类,覆盖其addInterceptors接口并注册我们自己的拦截器
@SpringBootConfiguration注解表明这是一个配置类
package com.datang.demo;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;@SpringBootConfiguration
public class WebAppConfig extends WebMvcConfigurationSupport {@AutowiredInterceptorConfig interceptorConfig;@Overridepublic void addInterceptors(InterceptorRegistry registry) {// 注册自定义拦截器,添加拦截路径和排除拦截路径registry.addInterceptor(interceptorConfig).addPathPatterns("/**").excludePathPatterns("/logger/**");}
}
2)直接实现WebMvcConfigurer
package com.datang.demo;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@SpringBootConfiguration
public class WebAppConfig implements WebMvcConfigurer {@AutowiredInterceptorConfig interceptorConfig;@Overridepublic void addInterceptors(InterceptorRegistry registry) {// 注册自定义拦截器,添加拦截路径和排除拦截路径registry.addInterceptor(interceptorConfig).addPathPatterns("/**").excludePathPatterns("/logger/**");}
}
运行结果如下:
这篇关于SpringBoot高版本添加拦截器,替代WebMvcConfigurerAdapter的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!