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>
-
創(chuàng)建攔截器
@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() + ", 請求的參數(shù)為:" + JSON.toJSONString(request.getParameterMap())); return true; } }
-
創(chuàng)建WebMvcConfigurer。
WebMvcConfigurer配置類其實是
Spring
內(nèi)部的一種配置方式镣奋,采用JavaBean
的形式來代替?zhèn)鹘y(tǒng)的xml
配置文件形式進行針對框架個性化定制币呵,可以自定義一些Handler,Interceptor侨颈,ViewResolver余赢,MessageConverter」福基于java-based方式的spring mvc配置妻柒,需要創(chuàng)建一個配置類并實現(xiàn)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("/**"); } }; } }
還有第二種方式實現(xiàn)耘分,直接用WebConfiguration implements WebMvcConfigurer 重寫addInterceptors方法