之前项目的springboot自定义拦截器使用的是继承WebMvcConfigurerAdapter重写常用方法的方式来实现的.静态文件不需要进行放行,springboot会自动帮你放行。
springboot2.0之后如果想要自定义的话就不可以了,需要手动放行静态资源。此处我是实现了WebMvcConfigurer来自定义拦截器(根据需求也可以继承WebMvcConfigurationSupport,此处不再赘述)。下面是实现代码
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//自定义一个视图拦截器,于springboot的自动配置同时生效,注意不要加EableConfiguration,
//否则springboot的自动配置不会生效
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
//注册登录拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("**")
.excludePathPatterns("/index.html","/user/login","/","/assters/**");
//拦截所有请求,将/index.html,/user/login,/,/assters/**排除在外。
}
}
注意:此处排除的"/assters/**“为我自己的静态资源文件夹,也就是在springboot项目的类路径下的static文件夹下的文件夹,不能写成”/static/**“因为在springboot2.0+之后springboot的自动配置的静态资源的映射路径中不在有static,所以在这里排除”/static/**"不会起作用。
我的拦截器
public class LoginHandlerInterceptor implements HandlerInterceptor {//我的拦截器,实现HandlerInterceptor接口
//重写preHandle
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("user");
if(user==null){
request.getSession().setAttribute("msg","没有权限访问");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else{
return true;
}
}
}
上面是我看sgg的视频,加上网上一些说法来写的,如有错误请指明。
附:难道我们都是一个老师教出来的?代码写的一样,注释也一样。。