- SpringBoot 2.x版本啟用攔截器配置盏浙,會(huì)顯示
WebMvcConfigurerAdapter
將被拋棄绅这,使用WebMvcConfigurationSupport替代
會(huì)導(dǎo)致靜態(tài)資源不能訪問的問題车荔。 - 發(fā)現(xiàn)只要繼承 WebMvcConfigurationSupport 并且將文件加入配置 甘耿,則在yml或properties中配置的相關(guān)內(nèi)容會(huì)失效搓茬。
- 解決辦法是需要重新指定靜態(tài)資源芽突。
示例如下
- 登錄攔截器
@Component
public class BaseInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(BaseInterceptor.class);
private static final String USER_AGENT = "user-agent";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String uri = request.getRequestURI();
String ip = IpUtil.getIpAddrByRequest(request);
logger.info("UserAgent: {}", request.getHeader(USER_AGENT));
logger.info("用戶訪問地址: {}, 來路地址: {}", uri, ip);
//請(qǐng)求攔截處理
HttpSession session = request.getSession();
User user = (User) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
if (uri.startsWith("/admin") && !uri.startsWith("/admin/login") && null == user) {
response.sendRedirect(request.getContextPath() + "/admin/login");
return false;
}
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 {
}
}
- 攔截器配置類
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Resource
private BaseInterceptor baseInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(baseInterceptor);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}