• 写一个简单食用的拦截器


    写个Filter继承OncePerRequestFilter重写doFilterInternal
    1、doFilterInternal方法
    1. @WebFilter(filterName = "tenantAuthCheckFilter", urlPatterns = {"/v1/url/*"})
    2. @Order(1)
    3. public class TenantFilter extends OncePerRequestFilter {
    4. @Autowired
    5. private ServiceA serviceA;
    6. @Autowired
    7. private ExcludePathsConfig excludePathsConfig;
    8. @Override
    9. protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
    10. String servletPath = request.getServletPath();
    11. String userId = request.getHeader("userId");
    12. if (!excludePathsConfig.getPaths().contains(servletPath)) {
    13. User user = ServiceA.getProdInst(prodInstId);
    14. if(user.getUserId!=userId){
    15. throw new Exception("当前用户没权限");
    16. }
    17. }
    18. filterChain.doFilter(request, response);
    19. }
    20. }

    2、 将applicaiton.yml下的配置读取成List

    1. @Component
    2. @ConfigurationProperties(prefix = "interceptorconfig.exclude")
    3. @Data
    4. public class ExcludePathsConfig {
    5. private List paths;
    6. }

    3、application.yml配置 

    1. interceptorconfig: # 拦截器配置
    2. exclude:
    3. paths:
    4. - /v1/url/userList # 不拦截这个接口
    5. - /v1/url/dict # 不拦截这个接口

    4、启动类增加ServletComponentScan()

    @ServletComponentScan(basePackages = {"cn.lihaiyu.test.*"})
    

    5、Filter抛出错误方案

    1. @RestController
    2. public class ErrorController extends BasicErrorController {
    3. public ErrorController() {
    4. super(new DefaultErrorAttributes(), new ErrorProperties());
    5. }
    6. @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    7. @Override
    8. public ResponseEntity> error(HttpServletRequest request) {
    9. Map errorAttributes = getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.EXCEPTION,ErrorAttributeOptions.Include.MESSAGE,ErrorAttributeOptions.Include.STACK_TRACE,ErrorAttributeOptions.Include.BINDING_ERRORS));
    10. HttpStatus status = getStatus(request);
    11. // 错误代码:-1
    12. String code = String.valueOf(ErrorType.SYS_ERROR.getCode());
    13. // 获取错误信息
    14. String message = errorAttributes.get("message").toString();
    15. ApiErrorResult apiErrorResult = new ApiErrorResult(code,message);
    16. return new ResponseEntity<>(apiErrorResult,status);
    17. }
    18. }
    1. public class ApiErrorResult extends LinkedHashMap {
    2. private static final String CODE_KEY = "code";
    3. private static final String MESSAGE_KEY = "message";
    4. public ApiErrorResult(String code, String message) {
    5. this.put(CODE_KEY,code);
    6. this.put(MESSAGE_KEY,message);
    7. }
    8. }

    6、需要注意的地方:

    ① 使用ServletComponentScan

    1. SpringBootApplication 上使用@ServletComponentScan 注解后
    2. Servlet可以直接通过@WebServlet注解自动注册
    3. Filter可以直接通过@WebFilter注解自动注册
    4. Listener可以直接通过@WebListener 注解自动注册

    原文链接:https://blog.csdn.net/qq_35574640/article/details/87936672

    ② 不要在Filter上面使用@Component,否则 urlPatterns 失效,会拦截所有的请求

    ③ 抛出错误的方法,filter内无法直接抛出错误,需要借助 BasicErrorController

  • 相关阅读:
    【论文阅读】Mastering the game of Go with deep neural networks and tree search
    一篇文章带您了解PHP数组
    WPF中如何设置自定义控件
    MCU如何选型?
    【Mysql】 InnoDB引擎深入- 行溢出
    windows WSL配置cuda,pytorch和jupyter notebook
    【Java基础面试三十五】、谈谈你对面向接口编程的理解
    互联网大厂测开领域调研
    【力扣10天SQL入门】Day3
    03uec++多人游戏【拥有莱福武器】
  • 原文地址:https://blog.csdn.net/Li_haiyu/article/details/126648773