• springboot之Filter的URI匹配规则


    @Slf4j
    public class AntPathMatcherTests {
        @Test
        public void matcher(){
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            log.info("/a是否匹配/a/*:{}",antPathMatcher.match("/a/*","/a"));//false
            log.info("/a/b是否匹配/a/*:{}",antPathMatcher.match("/a/*","/a/b"));//true
            log.info("/a是否匹配/a/bc/def:{}",antPathMatcher.match("/a/bc/def","/a"));//false
            log.info("/a/b/c是否匹配/a/*/def:{}",antPathMatcher.match("/a/*/def","/a/b/c"));//false
            log.info("/a/b/def是否匹配/a/*/def:{}",antPathMatcher.match("/a/*/def","/a/b/def"));//true
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    当我们想对某些uri过滤时就可以这样做
    yml配置过滤的uri或者url

    ignore:
      uri:
      - /api/test
      - /api/demo
      - /api/*/test
      - /api/demo/*
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    写一个过滤uri的配置类

    @Data
    @Configuration
    @ConfigurationProperties(prefix = "ignore") // 配置文件的前缀
    public class UriConfig {
        private List<String> uri;//等价于@Value("{ignore.uri}"),但是@Value多个要用切割的方式,这种方式直接拿就好。建议多个值需要切割时使用这种写法
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    使用过滤的uri的方法引入,如:filter过滤器

    @Component
    @WebFilter(urlPatterns = "/*", filterName = "DemoFilter")
    public class DemoFilter implements Filter{
    
    	@Resource
    	private UriConfig uriConfig;
    	
    	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain){
    		HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            
    		String requestURI = request.getRequestURI();//请求地址
    		AntPathMatcher antPathMatcher = new AntPathMatcher();
    		boolean passUri = uris.stream().anyMatch(uri -> antPathMatcher.match(uri,requestURI));
    		log.info(requestURI + "是否是滤地址:{}" , passUri);
    		filterChain.doFilter(request, response);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
  • 相关阅读:
    【Git命令】git reset与 git revert 简单示例
    软件测试面试遇到之redis要怎么测试?
    C# 设计模式 观察者模式示例
    设计模式:享元模式案例
    MM41/MM42/MM43零售物料主数据BAPI创建示例(WRF_MATERIAL_MAINTAINDATA_RT)
    团购列表.
    (附源码)node.js宠物医生预约平台 毕业设计 030945
    力扣刷题目录
    lotus windowPoSt 手动触发时空证明计算
    Vue之ElementUI实现登陆及注册
  • 原文地址:https://blog.csdn.net/weixin_43933728/article/details/127905109