• 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
  • 相关阅读:
    C++设计模式_10_ Prototype 原型模式(小模式,不太常用)
    react 配置react-router
    英语口语 - 连读
    托尔斯泰:生活中只有两种不幸
    洛谷_P8872
    OSG笔记:osgText::Font搜索路径及开发中的应用
    vue使用Echarts5实现词云图
    Ubuntu 安装谷歌拼音输入法
    红黑树详解
    (一)探索随机变量及其分布:概率世界的魔法
  • 原文地址:https://blog.csdn.net/weixin_43933728/article/details/127905109