SpringBoot 攔截器的簡單配置及用法
阿新 • • 發佈:2019-01-05
攔截器的使用場景
登陸驗證、許可權等都會用到攔截器
非同步任務的簡單配置
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 } }