如何解决如何判断请求URL中是否存在@PathVariable?
我正在尝试在网关上编写 api 权限过滤器。应禁止不具有特定角色的令牌访问资源。除了包含 @PathVariable
参数的 apis 之外,所有请求都已被有效过滤。例如,URI 为 /api/v1/query/{id}
的 api,参数 id
在某些情况下可能是 uuid
,而在其他情况下可能是 long
值。
除了添加越来越多的正则表达式模式之外,还有什么更好的方法吗?网关的总体目标是尽可能少地消耗时间。
解决方法
无论如何我想出了一个合适的解决方案。所有项目中的 @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,index);
System.out.println(subUrl);
int index2 = StringUtils.lastIndexOf(subUrl,"/");
String subOfSubUrl = StringUtils.substring(url,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
,很容易编写相关代码来检查角色。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。