Springboot攔截器的使用

Springboot攔截器的使用

  1. 引入springboot-starter-web
<code> <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>/<code>
  1. 創建攔截器 @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; } }
  2. 創建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方法


分享到:


相關文章: