自定义注解实现接口放行

自定义注解实现接口放行

通过自定义注解的方式实现请求接口放行

  1. 新建自定义注解
import java.lang.annotation.*;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IgnoreAuth {
   String value();
}

@Target({ElementType.METHOD}) 使用范围为方法
@Retention(RetentionPolicy.RUNTIME) 生命周期为运行时可以通过反射获取
@Documented 被包含在javadoc中

  1. 新建自定义拦截器 InterceptorConfig 继承 HandlerInterceptorAdapter
@Component
public class InterceptorConfig  extends HandlerInterceptorAdapter {
   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
   	 return false;
   }
}
  1. 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;
  1. 注解使用

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
   }

亲测有效,不贴测试结果了

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值