@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
}
}
当我们想对某些uri过滤时就可以这样做
yml配置过滤的uri或者url
ignore:
uri:
- /api/test
- /api/demo
- /api/*/test
- /api/demo/*
写一个过滤uri的配置类
@Data
@Configuration
@ConfigurationProperties(prefix = "ignore") // 配置文件的前缀
public class UriConfig {
private List<String> uri;//等价于@Value("{ignore.uri}"),但是@Value多个要用切割的方式,这种方式直接拿就好。建议多个值需要切割时使用这种写法
}
使用过滤的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);
}
}