spring boot攔截器 完成這個演示只需要三個檔案
第一個 攔截器配置 MvcConfigurer.java
@Configuration public class MvcConfigurer implements WebMvcConfigurer { //攔截器 @Override public void addInterceptors(InterceptorRegistry interceptorRegistry) { //給指定url增加攔截器 可將要攔截的Url搭配萬用字元寫在配置檔案中 /Index/** interceptorRegistry.addInterceptor(new FilterHandler()).addPathPatterns("/a"); } //.....其他更多全域性定製實現方法 }
第二個 攔截器邏輯 FilterHandler.java
public class FilterHandler implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { //在呼叫controller方法之前會呼叫此方法 //重定向到/c httpServletResponse.sendRedirect("/c"); return false; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { //在呼叫controller方法之後會呼叫此方法 } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { //頁面渲染完畢後會呼叫此方法 } }
第三個 業務訪問控制層 IndexController
@Controller public class IndexController { @RequestMapping("/a") @ResponseBody public String a(){ return "這是a方法"; } @RequestMapping("/b") @ResponseBody public String b(){ return "這是b方法"; } @RequestMapping("/c") @ResponseBody public String c(){ return "這是c方法 請你登陸"; } }
執行效果
本篇部落格碼雲地址:https://gitee.com/zhao-baolin/springboot_interceptor