最近,要和别的同事进行接口调试,然后暴露的接口不要登录验证.需要在拦截器的方法中添加一个白名单.
1.先编写接口PassPath
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface UrlPass {
}
2.在需要的方法上面添加注解@PassPath
3.在拦截器中对注解进行处理
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
String requestUrl = request.getServletPath();
/**
* 白名单,判断是否含有白名单注解PassPath
*/
if(AnnotationUtil.containUrlPass(object)){
return true;
}
}
public class AnnotationUtil {
/**
* 判断方法中是否含有passPath注解,如果有,就放行
* @param object
* @return
*/
public static boolean containUrlPass(Object object){
if(object instanceof HandlerMethod){
//将方法名称转换为对应的类型
HandlerMethod handlerMethod = (HandlerMethod) object;
//获取方法
Method method = handlerMethod.getMethod();
//获取方法上面所有注解并且遍历
Annotation[] annotations = method.getAnnotations();
//遍历注解
for (Annotation annotation : annotations) {
//如果注解包含可以通过的注解passPath,则直接放行
if(annotation.annotationType().equals(UrlPass.class)){
return true;
}
}
}
return false;
}
}