基于Ant路径匹配规则AntPathMatcher的注意事项
作者:豆角茄子子 发布时间:2021-11-19 03:58:16
AntPathMatcher前言
(1)SpringMVC的路径匹配规则是依照Ant的来的,实际上不只是SpringMVC,整个Spring框架的路径解析都是按照Ant的风格来的;
(2)AntPathMatcher不仅可以匹配Spring的@RequestMapping路径,也可以用来匹配各种字符串,包括文件路径等。
基本规则
(1)? 匹配一个字符(除过操作系统默认的文件分隔符)
(2)* 匹配0个或多个字符
(3)**匹配0个或多个目录
(4){spring:[a-z]+} 将正则表达式[a-z]+匹配到的值,赋值给名为 spring 的路径变量.
(PS:必须是完全匹配才行,在SpringMVC中只有完全匹配才会进入controller层的方法)
注意事项
(1)匹配文件路径,需要匹配某目录下及其各级子目录下所有的文件,使用/**/*而非*.*,因为有的文件不一定含有文件后缀;
(2)匹配文件路径,使用AntPathMatcher创建一个对象时,需要注意AntPathMatcher也有有参构造,传递路径分隔符参数pathSeparator,对于文件路径的匹配来说,则需要根据不同的操作系统来传递各自的文件分隔符,以此防止匹配文件路径错误。源码截图如下:
可以看到,AntPathMatcher默认路径分隔符为“/”,而在匹配文件路径时,需要注意Windows下路径分隔符为“\”,Linux下为“/”,写法即为:
AntPathMatcher matcher = new AntPathMatcher(File.separator);
AntPathMatcher matcher = new AntPathMatcher(System.getProperty("file.separator"));
(3)最长匹配规则(has more characters),即越精确的模式越会被优先匹配到。例如,URL请求/app/dir/file.jsp,现在存在两个路径匹配模式/**/*.jsp和/app/dir/*.jsp,那么会根据模式/app/dir/*.jsp来匹配。
测试用例
// test exact matching
assertTrue(pathMatcher.match("test", "test"));
assertTrue(pathMatcher.match("/test", "/test"));
assertTrue(pathMatcher.match("http://example.org", "http://example.org")); // SPR-14141
assertFalse(pathMatcher.match("/test.jpg", "test.jpg"));
assertFalse(pathMatcher.match("test", "/test"));
assertFalse(pathMatcher.match("/test", "test"));
// test matching with ?'s
assertTrue(pathMatcher.match("t?st", "test"));
assertTrue(pathMatcher.match("??st", "test"));
assertTrue(pathMatcher.match("tes?", "test"));
assertTrue(pathMatcher.match("te??", "test"));
assertTrue(pathMatcher.match("?es?", "test"));
assertFalse(pathMatcher.match("tes?", "tes"));
assertFalse(pathMatcher.match("tes?", "testt"));
assertFalse(pathMatcher.match("tes?", "tsst"));
// test matching with *'s
assertTrue(pathMatcher.match("*", "test"));
assertTrue(pathMatcher.match("test*", "test"));
assertTrue(pathMatcher.match("test*", "testTest"));
assertTrue(pathMatcher.match("test/*", "test/Test"));
assertTrue(pathMatcher.match("test/*", "test/t"));
assertTrue(pathMatcher.match("test/*", "test/"));
assertTrue(pathMatcher.match("*test*", "AnothertestTest"));
assertTrue(pathMatcher.match("*test", "Anothertest"));
assertTrue(pathMatcher.match("*.*", "test."));
assertTrue(pathMatcher.match("*.*", "test.test"));
assertTrue(pathMatcher.match("*.*", "test.test.test"));
assertTrue(pathMatcher.match("test*aaa", "testblaaaa"));
assertFalse(pathMatcher.match("test*", "tst"));
assertFalse(pathMatcher.match("test*", "tsttest"));
assertFalse(pathMatcher.match("test*", "test/"));
assertFalse(pathMatcher.match("test*", "test/t"));
assertFalse(pathMatcher.match("test/*", "test"));
assertFalse(pathMatcher.match("*test*", "tsttst"));
assertFalse(pathMatcher.match("*test", "tsttst"));
assertFalse(pathMatcher.match("*.*", "tsttst"));
assertFalse(pathMatcher.match("test*aaa", "test"));
assertFalse(pathMatcher.match("test*aaa", "testblaaab"));
// test matching with ?'s and /'s
assertTrue(pathMatcher.match("/?", "/a"));
assertTrue(pathMatcher.match("/?/a", "/a/a"));
assertTrue(pathMatcher.match("/a/?", "/a/b"));
assertTrue(pathMatcher.match("/??/a", "/aa/a"));
assertTrue(pathMatcher.match("/a/??", "/a/bb"));
assertTrue(pathMatcher.match("/?", "/a"));
// test matching with **'s
assertTrue(pathMatcher.match("/**", "/testing/testing"));
assertTrue(pathMatcher.match("/*/**", "/testing/testing"));
assertTrue(pathMatcher.match("/**/*", "/testing/testing"));
assertTrue(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla"));
assertTrue(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla/bla"));
assertTrue(pathMatcher.match("/**/test", "/bla/bla/test"));
assertTrue(pathMatcher.match("/bla/**/**/bla", "/bla/bla/bla/bla/bla/bla"));
assertTrue(pathMatcher.match("/bla*bla/test", "/blaXXXbla/test"));
assertTrue(pathMatcher.match("/*bla/test", "/XXXbla/test"));
assertFalse(pathMatcher.match("/bla*bla/test", "/blaXXXbl/test"));
assertFalse(pathMatcher.match("/*bla/test", "XXXblab/test"));
assertFalse(pathMatcher.match("/*bla/test", "XXXbl/test"));
assertFalse(pathMatcher.match("/????", "/bala/bla"));
assertFalse(pathMatcher.match("/**/*bla", "/bla/bla/bla/bbb"));
assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/"));
assertTrue(pathMatcher.match("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing"));
assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing"));
assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg"));
assertTrue(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing/"));
assertTrue(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing"));
assertTrue(pathMatcher.match("*bla*/**/bla/**", "XXXblaXXXX/testing/testing/bla/testing/testing"));
assertFalse(pathMatcher.match("*bla*/**/bla/*", "XXXblaXXXX/testing/testing/bla/testing/testing"));
assertFalse(pathMatcher.match("/x/x/**/bla", "/x/x/x/"));
assertTrue(pathMatcher.match("/foo/bar/**", "/foo/bar")) ;
assertTrue(pathMatcher.match("", ""));
assertTrue(pathMatcher.match("/{bla}.*", "/testing.html"));
spring url匹配工具类----AntPathMatcher
在gateway进行授权认证时,有些请求url需要过滤掉,针对带/service/{id}/user-info这种带操作符的请求,需要特殊处理----AntPathMatcher就上场啦
具体使用场景
1.登录授权验证:过滤掉登录请求,一些资源获取请求
2.请求接口日志打印:过滤掉文件上传和下载的一些请求,requestBody里的文件流会被异常修改
具体代码:
请求body的二次写入
@Component
public class CachePostBodyFilter implements GlobalFilter, Ordered {
private final List<HttpMessageReader<?>> messageReaders;
public CachePostBodyFilter() {
this.messageReaders = HandlerStrategies.withDefaults().messageReaders();
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
if (FilterUrl.excludeUrls(new FilterUrl(request.getPath().toString(), request.getMethod()))) {
return chain.filter(exchange);
}
if (Objects.equals(request.getMethod(), HttpMethod.POST)) {
ServerRequest serverRequest = ServerRequest.create(exchange,
messageReaders);
Mono<String> modifiedBody = serverRequest.bodyToMono(String.class)
.flatMap(body -> {
exchange.getAttributes().put(RequestConstants.REQUEST_BODY, body);
return Mono.just(body);
});
BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody, String.class);
HttpHeaders headers = new HttpHeaders();
headers.putAll(exchange.getRequest().getHeaders());
// the new content type will be computed by bodyInserter
// and then set in the request decorator
headers.remove(HttpHeaders.CONTENT_LENGTH);
CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);
return bodyInserter.insert(outputMessage, new BodyInserterContext()).
then(Mono.defer(() -> {
ServerHttpRequest decorator = decorate(exchange, headers,
outputMessage);
return chain.filter(exchange.mutate().request(decorator).build());
}));
}
return chain.filter(exchange);
}
ServerHttpRequestDecorator decorate(ServerWebExchange exchange, HttpHeaders headers,
CachedBodyOutputMessage outputMessage) {
return new ServerHttpRequestDecorator(exchange.getRequest()) {
@Override
public HttpHeaders getHeaders() {
long contentLength = headers.getContentLength();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.putAll(headers);
if (contentLength > 0) {
httpHeaders.setContentLength(contentLength);
} else {
httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
}
return httpHeaders;
}
@Override
public Flux<DataBuffer> getBody() {
return outputMessage.getBody();
}
};
}
@Override
public int getOrder() {
return -8;
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FilterUrl {
private String url;
private HttpMethod method;
public static boolean excludeUrls(FilterUrl targetUrl) {
List<FilterUrl> excludeUrls = Lists.newArrayList();
excludeUrls.add(new FilterUrl("/api/v1/service/users", HttpMethod.POST));
excludeUrls.add(new FilterUrl("/api/v1/service/terms/{termId}/export", HttpMethod.GET));
AntPathMatcher antPathMatcher = new AntPathMatcher();
return excludeUrls.stream()
.anyMatch(url -> antPathMatcher.match(url.getUrl(), targetUrl.getUrl()) && url.getMethod().equals(targetUrl.getMethod()));
}
}
来源:https://www.cnblogs.com/songzehao/p/10854280.html


猜你喜欢
- 一.应用场景平时在建对象表的时候都会有最后修改时间,最后修改人这两个字段,对于这些大部分表都有的字段,每次在新增和修改的时候都要考虑到这几个
- 前言在Java中,集合和数组是我们经常会用到的数据结构,需要经常对他们做增、删、改、查、聚合、统计、过滤等操作。相比之下,关系型数据库中也同
- Java环境部署下载所需软件和依赖安装 jdk路径可选别的盘。但是指向时得注意我自己时装在 F 盘的,在f盘里新建文件夹 Java,Java
- 当我们在项目中登录使用验证码的时候,不妨试试Kaptcha生成验证码,非常简单1、首先,我们在pom.xml文件中引入kaptcha的mav
- JSON.toJSONString()空字段不忽略修改使用JSON.toJSONString(object)方法,返回的json中,默认会将
- 这篇文章主要介绍了Spring 自动装配的二义性实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的
- 一,SQL注入–1,需求–1,利用jdbc查询user的信息,如果信息正确就登录,否则提示错误–1,创建user表,指定字段id name
- 一、前言大家好,我是一个初学C语言的小菜狗,是否大家在平时的做题中会遇到和我一样的烦恼,题目的代码已经基本完成,但是在输出时候,总是和题目给
- 一、什么是跨域1.1、为什么会出现跨域问题出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心
- 网络应用模式主要有:主机/终端模式:集中计算,集中管理;客户机/服务器(Client/Server,简称C/S)模式:分布计算,分布管理;浏
- Java实现PC微信扫码支付做一个电商网站支付功能必不可少,那我们今天就来盘一盘微信支付。微信支付官方网站业务流程:开发指引文档支付服务开发
- Java解压缩zip - 多个文件(包括文件夹),对多个文件和文件夹进行压缩,对复杂的文件目录进行解压。压缩方法使用的是可变参数,可以压缩1
- 本节我们开始自我实现我们自己okhttp框架中的每个 * 。先简单回顾一下各个 * 的作用:RetryAndFollowUpIntercep
- 一、新建BeanUtil类import lombok.extern.slf4j.Slf4j;import org.springframewo
- 定义强引用是使用最普遍的引用。如果一个对象具有强引用,那垃圾回收器宁愿抛出OOM(OutOfMemoryError)也不会回收它。说明不要被
- 一、前言做新应用就是这样,会遇到各种问题,昨天刚解决了加载某一个类时候抛出了 class is not visible from class
- 1.添加命名空间System.IO;System.Text;2.文件的读取(1).使用FileStream类进行文件的读取,并将它转换成ch
- 这是一个自定义view画圆,对于初学自定义view的小伙伴这是一个很好的帮助。 看图代码:package sjx.com.custonvie
- Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而
- 第一个System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);&nb