自定义注解实现接口放行
通过自定义注解的方式实现请求接口放行
- 新建自定义注解
import java.lang.annotation.*;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IgnoreAuth {
String value();
}
@Target({ElementType.METHOD}) 使用范围为方法
@Retention(RetentionPolicy.RUNTIME) 生命周期为运行时可以通过反射获取
@Documented 被包含在javadoc中
- 新建自定义拦截器 InterceptorConfig 继承 HandlerInterceptorAdapter
@Component
public class InterceptorConfig extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
return false;
}
}
- preHandle 方法
//注解实现接口放行 RequestMapping+IgnoreAuth = 请求url
HandlerMethod handlerMethod = (HandlerMethod)handler;
Method method = handlerMethod.getMethod();
IgnoreAuth annotation = method.getAnnotation(IgnoreAuth.class);
if (DataHelpers.isNotEmpty(annotation)) {
//IgnoreAuth的值
String value = annotation.value();
//请求的url /test-mapping/getOne
String url= request.getRequestURI();
if (url.equals(value )) {
return true;
}
return false;
- 注解使用
4.1方法示例 注解上的值直接填写完整url
@ApiOperation(value = "详情")
@GetMapping(value = "/getOne")
@ApiImplicitParam(name = "id", value = "主键id")
@IgnoreAuth("/test-mapping/getOne")
public void getOne(String id) {
}
4.2也可以直接获取到Controller上面的RequestMapping
类示例
@RequestMapping("/test-mapping")
方法示例
@ApiOperation(value = "详情")
@GetMapping(value = "/getOne")
@ApiImplicitParam(name = "id", value = "主键id")
@IgnoreAuth("/getOne")
public void getOne(String id) {
}
//获取RequestMapping的值 /test-mapping
RequestMapping declaredAnnotation = handlerMethod.getBeanType().getDeclaredAnnotation(RequestMapping.class);
if (DataHelpers.isNotEmpty(declaredAnnotation)) {
String requestMapping = declaredAnnotation.value()[0];//test-mapping
}
亲测有效,不贴测试结果了