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