Spring boot拦截器的实现
Spring boot自带HandlerInterceptor,可通过继承它来实现拦截功能,其的功能跟过滤器类似,但是提供更精细的的控制能力。
1.注册拦截器
1 @Configuration 2 public class MyWebAppConfigurer extends WebMvcConfigurerAdapter { 3 @Bean //把我们的拦截器注入为bean 4 public HandlerInterceptor getMyInterceptor(){ 5 return new Interceptor(); 6 } 7 8 @Override 9 public void addInterceptors(InterceptorRegistry registry) { 10 // addPathPatterns 用于添加拦截规则, 这里假设拦截 /url 后面的全部链接 11 // excludePathPatterns 用户排除拦截 12 registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**"); 13 super.addInterceptors(registry); 14 } 15 }
2.创建拦截器,写要过滤的请求等
1 public class Interceptor implements HandlerInterceptor { 2 3 private Logger logger = LoggerFactory.getLogger(URLInterceptor.class); 4 5 public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) 6 throws Exception { 7 // TODO Auto-generated method stub 8 9 } 10 11 public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) 12 throws Exception { 13 // TODO Auto-generated method stub 14 15 } 16 17 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { 18 String flag = null; 19 flag = request.getParameter("auth"); 20 if(StringUtils.isEmpty(flag) || !flag.equals("php")){ 21 logger.error("error-auth:{}", flag); 22 return false; 23 } else { 24 logger.info("通过校验!"); 25 return true; 26 } 27 } 28 }
3.取消拦截
上面是拦截所有接口,如果想某个接口取消拦截,怎么办?
新建一个类
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface UnAuthority { }
4.在不需要拦截的方法上面添加新增的注解,如下
@UnAuthority @RequestMapping("/hello") public String hello(){ return "Hello World"; }
5.修改拦截器的preHandle方法,如下
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { // 检测请求的方法是否有UnAuthority注解,有注解不拦截,直接放行,返回true。 HandlerMethod handlerMethod = (HandlerMethod)arg2; Method method = handlerMethod.getMethod(); UnAuthority unAuthority = method.getAnnotation(UnAuthority.class); if(unAuthority != null ){ return true; } String flag = null; flag = request.getParameter("auth"); if(StringUtils.isEmpty(flag) || !flag.equals("php")){ logger.error("error-auth:{}", flag); return false; } else { logger.info("通过校验!"); return true; } }
6.不需要auth参数访问/hello接口,成功。
新增了无需拦截的注解后,就可以根据业务需求哪些是需要拦截,哪些是不需要拦截
参考:https://blog.csdn.net/wsbgmofo/article/details/79151947
来源:https://www.cnblogs.com/heqiyoujing/p/9436762.html