Springboot拦截器的使用
- 引入springboot-starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>org.springframework.boot</artifactId>
<groupId>spring-boot-start-tomcat</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
-
创建拦截器
@Component public class LogInterceptor implements HandlerInterceptor { static Logger logger = LoggerFactory.getLogger(LoggerFactory.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("请求的路径为: "+ request.getRequestURI() + ", 请求的参数为:" + JSON.toJSONString(request.getParameterMap())); return true; } }
-
创建WebMvcConfigurer。
WebMvcConfigurer配置类其实是
Spring
内部的一种配置方式,采用JavaBean
的形式来代替传统的xml
配置文件形式进行针对框架个性化定制,可以自定义一些Handler,Interceptor,ViewResolver,MessageConverter。基于java-based方式的spring mvc配置,需要创建一个配置类并实现WebMvcConfigurer
接口;@Configuration public class RequestLogConfiguration { @Autowired private LogInterceptor logInterceptor; @Bean public WebMvcConfigurer webMvcConfigurer(){ return new WebMvcConfigurer() { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(logInterceptor).addPathPatterns("/**"); } }; } }
还有第二种方式实现,直接用WebConfiguration implements WebMvcConfigurer 重写addInterceptors方法