现在有很多项目中还在使用interceptor拦截器,所以一开始在做登录的时候我就使用了它,并做一次记录
1.(拦截器设置)创建一个AuthorityInterceptor类实现HandlerInterceptor接口
@Slf4j
@Component
public class AuthorityInterceptor implements HandlerInterceptor{
private static final Set<String> NOT_INTERCEPT_URI = new HashSet<>();//不拦截的URI
static {
NOT_INTERCEPT_URI.add("/login");
NOT_INTERCEPT_URI.add("/userLogin");
}
/**
* 在请求处理之前进行调用(Controller方法调用之前)
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws IOException {
String uri = request.getRequestURI();
log.info("uri :" + uri);
if (NOT_INTERCEPT_URI.contains(uri)) {
log.info("不拦截" + uri);
return true;
}
log.info("拦截" + uri);
User userInfo = (User) request.getSession().getAttribute("user");
if (userInfo == null) {
//throw new RuntimeException("用户未登陆");
response.sendRedirect("/login");
}
return true;
}
/**
* 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
*/
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv){
}
/**
* 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行
* (主要是用于进行资源清理工作)
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex){
}
}
2.拦截器设置拦截静态资源
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
public void addInterceptors(InterceptorRegistry registry) {
// 添加拦截器,配置拦截地址
registry.addInterceptor(new AuthorityInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/login","/userLogin")
.excludePathPatterns("/image/**");
}
/**
* 继承WebMvcConfigurationSupport类会导致自动配置失效
* 所以这里要指定默认的静态资源的位置
* @param registry
*/
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/resources/") //classpath要带上,因为boot项目默认的
.addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}