本网站(662p.com)打包出售,且带程序代码数据,662p.com域名,程序内核采用TP框架开发,需要联系扣扣:2360248666 /wx:lianweikj
精品域名一口价出售:1y1m.com(350元) ,6b7b.com(400元) , 5k5j.com(380元) , yayj.com(1800元), jiongzhun.com(1000元) , niuzen.com(2800元) , zennei.com(5000元)
需要联系扣扣:2360248666 /wx:lianweikj
详解Java拦截器以及自定义注解的使用
talkchan · 354浏览 · 发布于2021-12-22 +关注

这篇文章主要为大家介绍了Java拦截器以及自定义注解的使用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

1,设置预处理,设置不需要拦截的请求

@Component
public class MyWebConfig implements WebMvcConfigurer {
  private final UserTokenInterceptor userTokenInterceptor;
  private final SecurityInterceptor securityInterceptor;
  public MyWebConfig(
      UserTokenInterceptor userTokenInterceptor, SecurityInterceptor securityInterceptor) {
    this.userTokenInterceptor = userTokenInterceptor;
    this.securityInterceptor = securityInterceptor;
  }
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    // 定义排除swagger访问的路径配置
    String[] swaggerExcludes =
        new String[] {"/swagger-ui.html", "/swagger-resources/**", "/webjars/**"};
    registry
        .addInterceptor(userTokenInterceptor)
        .addPathPatterns("/**")
        .excludePathPatterns(
            "/user/login", "/static/**", "/*.html", "/*.ico", "/*.json", "/*.png", "/heartbeat/**")
        .excludePathPatterns(swaggerExcludes);
    registry
        .addInterceptor(securityInterceptor)
        .addPathPatterns("/maintain/**", "/user/**")
        .excludePathPatterns("/user/login");
  }
}


 

2.UserTokenInterceptor ,securityInterceptor分别处理不同的请求拦截,执行不同的拦截逻辑。

2个处理的类请求上可以有交集,2个处理类都执行。

@Component
public class UserTokenInterceptor implements HandlerInterceptor {
  private final EmpInfoService empInfoService;
  public UserTokenInterceptor(EmpInfoService empInfoService) {
    this.empInfoService = empInfoService;
  }
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    // 校验handler是否是HandlerMethod
    if (!(handler instanceof HandlerMethod)) {
      return true;
    }
    // 从请求头中获取token
    String token = request.getHeader("Authorization");
    /**
     * update:2021/11/30 ShengJieLi
     * 增加逻辑:Authorization的值不为本系统生成的token时,解密Authorization,获取token并验证
     */
    if (StrUtil.isNotEmpty(token)) {
      EmpInfo securityEmployee = empInfoService.queryToken(token);
      if(securityEmployee != null){
        // token有效
        String ref = empInfoService.isRef(token);
        if (StrUtil.isNotBlank(ref)) {
          response.setHeader("Access-Control-Expose-Headers", "token");
          response.addHeader("token", ref);
        }
      }else{
        //Authorization为PBE加密数据
        securityEmployee = empInfoService.analyticQueryToken(token,response);
      }
      if (securityEmployee != null) {
        // token有效
        // 将User对象放入到ThreadLocal中
        UserLocal.set(securityEmployee);
        return true;
      }
      return false;
    }
//    String s = JSONUtil.toJsonStr(ResponseResult.error(ErrorCode.TOKEN_ERROR));
//    response.setContentType("text/html;charset=UTF-8");
//    JSONUtil.toJsonStr(s, response.getWriter());
//    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    InterceptorExceptionResolver.interceptorError(response,ErrorCode.TOKEN_ERROR);
    //update 结束
    return false;
  }
  @Override
  public void afterCompletion(
      HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
      throws Exception {
    // 响应结束后刪除對象
    UserLocal.remove();
  }
}

@SecurityGrade({"SUPER_ADMIN", "SYSTEM_ADMIN"})
public class SecurityController {
  private final EmpInfoService empInfoService;
  public SecurityController(EmpInfoService empInfoService) {
    this.empInfoService = empInfoService;
  }
  @GetMapping("getUserInformation")
  @ApiOperation("登陸用户信息")
  @NoAuthorization
  public ResponseResult getUserInformation(@ApiIgnore HttpServletResponse response) {
    return empInfoService.getUserInformation(response);
  }
}


 

3.关于注解的使用

@SecurityGrade({"SUPER_ADMIN", "SYSTEM_ADMIN"})
public class SecurityController {
  private final EmpInfoService empInfoService;
  public SecurityController(EmpInfoService empInfoService) {
    this.empInfoService = empInfoService;
  }
  @GetMapping("getUserInformation")
  @ApiOperation("登陸用户信息")
  @NoAuthorization
  public ResponseResult getUserInformation(@ApiIgnore HttpServletResponse response) {
    return empInfoService.getUserInformation(response);
  }
}


method.getMethodAnnotation(SecurityGrade.class) 获得注解信息,methodAnnotation.value()获得注解内容"SUPER_ADMIN", "SYSTEM_ADMIN"。 


相关推荐

PHP实现部分字符隐藏

沙雕mars · 1312浏览 · 2019-04-28 09:47:56
Java中ArrayList和LinkedList区别

kenrry1992 · 896浏览 · 2019-05-08 21:14:54
Tomcat 下载及安装配置

manongba · 957浏览 · 2019-05-13 21:03:56
JAVA变量介绍

manongba · 953浏览 · 2019-05-13 21:05:52
什么是SpringBoot

iamitnan · 1076浏览 · 2019-05-14 22:20:36
加载中

0评论

评论
大家好,我是一名专注技术开发的技术屌丝,有什么问题可以互相交流,一起学习进步,谢谢。
分类专栏
小鸟云服务器
扫码进入手机网页