目录
1.自定义拦截器
2. 静态资源被拦截
3.从过滤器中去除静态文件
4.静态文件404解决
5.补充一下
6.遗留问题现象
1.自定义拦截器
自定义XXInterceptor实现HandlerInterceptor接口,在发送请求之前拦截,所以在preHandle方法内完善相应的逻辑代码,这里举例代码是从session中取userName这个先前存入session中的值,存在返回Ture,不存在返回false拦截器生效。
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Object userName = session.getAttribute("userName");
return userName!=null;
}
@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 MyMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//所有资源做拦截,除了登录和首页
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/","/user/login");
}
}
2. 静态资源被拦截
Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://localhost:8080/asserts/css/bootstrap.min.css".、
Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://localhost:8080/asserts/css/signin.css".
登录首页能够访问,但是其中的CSS样式没有能够加载。
出现 Resource interpreted as Stylesheet but transferred with MIME type text/plain
查阅相关资料说过滤器或者某个地方对所有的资源请求全部转为了text/html,那么我们就有两种解决方案
1.将静态资源从过滤器中除去(这里讲述这一种方法)
2.把非html文件的请求,例如CSS,Js的请求就保持原来的状态
3.从过滤器中去除静态文件
1.将静态文件所在文件从过滤器中去除,excludePathPatterns("/static/**");
(注意这块不能写成excludePathPatterns(classpath:"/static/**"))
2.实现addResourceHandlers方法
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/","/user/login","/static/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
4.静态文件404解决
因为我们配置的是从static文件下找,html引用CSS是从asserts文件下找,所以会找不到,修改引入文件路径即可,路径前面加上/static,修改完之后不要忘了ctrl+f9重新bulid一下。
http://localhost:8080/asserts/js/Chart.min.js net::ERR_ABORTED 404
<link href="asserts/css/bootstrap.min.css" th:href="@{/asserts/css/bootstrap.min.css}" rel="stylesheet">
<link href="asserts/css/bootstrap.min.css" th:href="@{/static/asserts/css/bootstrap.min.css}" rel="stylesheet">
5.补充一下
以下是addResourceHandlers方法中registy实例调用的两个方法的作用。
6.遗留问题现象
在浏览器存在session缓存的情况下,即拦截器返回ture的情况下,不把静态资源从拦截器中移除页面是正常的 ,怀疑是thymeleaf等解析器做了解析,而在拦截器拦截的情况thymeleaf等解析器没有发挥作用。(猜想)这种情况还有待研究。。。