SpringBoot的攔截器
阿新 • • 發佈:2018-12-22
其實SpringBoot和SpringMVC的攔截器是一樣的,SpringBoot只是拋棄了XML配置,在Java類裡面完成配置而已。
程式碼示例:
1、建立我們自己的攔截器類並實現 HandlerInterceptor 介面,LoginInterceptor類、
/** * @author Tang Haorong * @create 2018-12-22 15:37 * @name */ public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("已經進入攔截器..."); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("請求處理之後進行呼叫"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("整個請求結束之後被呼叫"); } }
2、建立一個Java類繼承WebMvcConfigurationSupport,並重寫 addInterceptors 方法。之前好像是繼承WebMvcConfigurerAdapter介面,但是現在好像不推薦使用這個了。WebConfig類:
/** * @author Tang Haorong * @create 2018-12-22 15:32 * @name */ @Configuration //將其變成配置類 public class WebConfig extends WebMvcConfigurationSupport { @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/login"); } }
如果有需要攔截多個路徑也可以寫成如下格式:
/** * @author Tang Haorong * @create 2018-12-22 15:32 * @name */ @Configuration //將其變成配置類 public class WebConfig extends WebMvcConfigurationSupport { //需要攔截的路徑 String[] addPathPatterns={ "/**" }; //不攔截的路徑 String[] excludePathPatterns={ "/hello", "/login" }; @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()) .addPathPatterns(addPathPatterns) .excludePathPatterns(excludePathPatterns); } }
Controller類:
/**
* @author Tang Haorong
* @create 2018-12-22 15:31
* @name
*/
@RestController
public class LoginController {
@GetMapping(value = "/login")
public String login(){
return "login request not intercept";
}
}
然後執行啟動類訪問:http://localhost:8080/loginlogin,由於這個請求是被攔截的,所以會進入LoginInterceptor攔截器中,控制檯輸出:
如果需要 WebMvcConfigurationSupport的更多用法,大家百度一下便知。