在Spring Boot中設(shè)置了HandlerInterceptor,發(fā)現(xiàn)對(duì)于js、css等文件都沒有起作用。
定義一個(gè)HandlerInterceptor
public class FooInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("foo");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
將HandlerInterceptor匹配到所有路徑
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new FooInterceptor())
.addPathPatterns("/**");
}
}
這時(shí)雖然PathPatterns設(shè)置了“/**”,但是發(fā)現(xiàn)FooInterceptor對(duì)靜態(tài)資源沒有起作用。這時(shí)看看addInterceptors方法上的注釋。
Add Spring MVC lifecycle interceptors for pre- and post-processing of controller method invocations. Interceptors can be registered to apply to all requests or be limited to a subset of URL patterns.
Note that interceptors registered here only apply to controllers and not to resource handler requests. To intercept requests for static resources either declare a MappedInterceptor bean or switch to advanced configuration mode by extending WebMvcConfigurationSupport and then override resourceHandlerMapping.
說明它只對(duì)controller起作用,如果想對(duì)靜態(tài)資源起作用,簡(jiǎn)單的方法是添加一個(gè)MappedInterceptor bean。
@Configuration
public class WebConfig {
@Bean
public MappedInterceptor getMappedInterceptor() {
return new MappedInterceptor(new String[] { "/**" }, new FooInterceptor());
}
}