攔截器的使用場景
登陸驗證、權限等都會用到攔截器
異步任務的簡單配置
1.在任務類增加註解 @Configuration 繼承 WebMvcConfigurerAdapter 代表配置攔截器的適配器
2.重寫 addInterceptors 添加需要的攔截器地址及需要排除的攔截地址
實例
適配器中重寫addInterceptors 配置我們需要攔截和不需要攔截的東西 注意:addPathPatterns("/*/**") 可以攔截所有請求
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
/**
* 攔截器按照順序執行
*addPathPatterns 用於添加攔截規則
*excludePathPatterns 用於排除攔截
*/
registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**")
.excludePathPatterns("/three/**");
registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**")
.addPathPatterns("/one/**");
.addPathPatterns("/three/**");
super.addInterceptors(registry);
}
}
攔截器寫法(以第一個攔截器爲例)
public class OneInterceptor implements HandlerInterceptor {
/**
* 在請求處理之前進行調用(Controller方法調用之前)
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object object) throws Exception {
System.out.println("被one攔截,放行...");
return true;
}
/**
* 請求處理之後進行調用,但是在視圖被渲染之前(Controller方法調用之後)
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object object, ModelAndView mv)
throws Exception {
// TODO Auto-generated method stub
}
/**
* 在整個請求結束之後被調用,也就是在DispatcherServlet 渲染了對應的視圖之後執行
* (主要是用於進行資源清理工作)
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object object, Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
}