详解Java拦截器以及自定义注解的使用

 更新时间:2022年01月10日 08:46:14   作者:李三岁yep  
这篇文章主要为大家介绍了Java拦截器以及自定义注解的使用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助<BR>

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"。

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

相关文章

  • 深入理解Java序列化与反序列化

    深入理解Java序列化与反序列化

    今天教大家深入理解Java的序列化与反序列化,文中介绍的非常详细,有很多代码示例,对正在学习Java的小伙伴们很有帮助,需要的朋友可以参考下
    2021-05-05
  • idea 2023.1字体设置及自动调整大小的图文教程

    idea 2023.1字体设置及自动调整大小的图文教程

    这篇文章主要介绍了idea 2023.1字体设置及自动调整大小的教程,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友可以参考下
    2023-07-07
  • Java String初始化String域例题解析

    Java String初始化String域例题解析

    这篇文章主要介绍了Java String初始化String域例题解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • 详解使用IntelliJ IDEA新建Java Web后端resfulAPI模板

    详解使用IntelliJ IDEA新建Java Web后端resfulAPI模板

    这篇文章主要介绍了详解使用IntelliJ IDEA新建Java Web后端resfulAPI模板,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • 关于Spring Cloud的熔断器监控问题

    关于Spring Cloud的熔断器监控问题

    Turbine是一个聚合Hystrix监控数据的工具,它可将所有相关/hystrix.stream端点的数据聚合到一个组合的/turbine.stream中,从而让集群的监控更加方便,接下来通过本文给大家介绍Spring Cloud的熔断器监控,感兴趣的朋友一起看看吧
    2022-01-01
  • C++内存管理看这一篇就够了

    C++内存管理看这一篇就够了

    这篇文章主要介绍了C/C++中的内存管理小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-08-08
  • Java程序中使用JavaMail发送带图片和附件的邮件

    Java程序中使用JavaMail发送带图片和附件的邮件

    这篇文章主要介绍了Java程序中使用JavaMail发送带图片和附件的邮件,JavaMail是专门用来处理邮件的Java API,需要的朋友可以参考下
    2015-11-11
  • Springboot项目实现将类从@ComponentScan中排除

    Springboot项目实现将类从@ComponentScan中排除

    这篇文章主要介绍了Springboot项目实现将类从@ComponentScan中排除,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • java结合keytool如何实现非对称加密与解密详解

    java结合keytool如何实现非对称加密与解密详解

    这篇文章主要给大家介绍了关于java结合keytool如何实现非对称加密与解密的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友下面随着小编来一起学习学习吧
    2018-08-08
  • Java汉字转成汉语拼音工具类

    Java汉字转成汉语拼音工具类

    这篇文章主要为大家详细介绍了Java汉字转成汉语拼音工具类,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-05-05

最新评论