現在有很多項目中還在使用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);
}
}