Spring boot拦截器的实现

时间:2023-03-08 16:47:12

Spring boot拦截器的实现

Spring boot自带HandlerInterceptor,可通过继承它来实现拦截功能,其的功能跟过滤器类似,但是提供更精细的的控制能力。

1.注册拦截器

 @Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Bean //把我们的拦截器注入为bean
public HandlerInterceptor getMyInterceptor(){
return new Interceptor();
} @Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns 用于添加拦截规则, 这里假设拦截 /url 后面的全部链接
// excludePathPatterns 用户排除拦截
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
}

2.创建拦截器,写要过滤的请求等

 public class Interceptor implements HandlerInterceptor {

     private Logger logger = LoggerFactory.getLogger(URLInterceptor.class);

     public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub } public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub } public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
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;
}
}
}

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.****.net/wsbgmofo/article/details/79151947