无论如何,我想出了一个合适的解决方案。所有项目中的@PathVariable 位于URL 的最后或最后两部分。例如/api/v1/data/query/{uid}/{pid} 或类似的东西。所以我们可以使用 Apache Common 的 StringUtils#lastIndexOf() 和 StringUtils#substring() 来消除这部分。
要编写演示代码,请同时导入 Hutool 和 Commons-Lang3。
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
import cn.hutool.core.util.IdUtil;
import org.apache.commons.lang3.StringUtils;
public class StringDemo {
public static void main(String[] args) {
String url = "http://localhost:8080/api/v1/data/query/" + IdUtil.simpleUUID() + "/" + IdUtil.getSnowflake(1L, 16).nextId();
System.out.println(url);
int index = StringUtils.lastIndexOf(url, "/");
String subUrl = StringUtils.substring(url, 0, index);
System.out.println(subUrl);
int index2 = StringUtils.lastIndexOf(subUrl, "/");
String subOfSubUrl = StringUtils.substring(url, 0, index2);
System.out.println(subOfSubUrl);
}
}
结果如下:
http://localhost:8080/api/v1/data/query/19280769925f43d98b2af405579955ac/1356927788629626880
http://localhost:8080/api/v1/data/query/19280769925f43d98b2af405579955ac
http://localhost:8080/api/v1/data/query
通过将uri简化为最简单,在我的例子中是/api/v1/data/query,很容易编写相关代码来检查角色。