1:編寫一個類 實現 HandlerInterceptor接口spring
@Componentpublic class TestInterceptor implements HandlerInterceptor { //前置方法 進入controller以前執行 可用於校驗token權限 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //controller執行以前,進行攔截的業務代碼
return true;//放行 }
//後置方法 controller執行以後執行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { }
//視圖渲染後執行方法 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
2:註冊攔截器到spring容器 springboot
編寫一個配置類,實現WebMvcConfigurer接口ide
/** * springboot將攔截器注入spring容器 */ @Configuration public class WebConfig implements WebMvcConfigurer { @Autowired private TestInterceptor testInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { //攔截器攔截全部路徑 registry.addInterceptor(testInterceptor).addPathPatterns("/**"); } }