Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如何判断请求URL中是否存在@PathVariable?_Spring_Spring Boot_Api Gateway - Fatal编程技术网

Spring 如何判断请求URL中是否存在@PathVariable?

Spring 如何判断请求URL中是否存在@PathVariable?,spring,spring-boot,api-gateway,Spring,Spring Boot,Api Gateway,我正在尝试在网关上编写api权限筛选器。应该禁止不带有特定角色的令牌访问资源。除了包含@PathVariable参数的API之外,所有请求都已被有效过滤。例如,URI为/api/v1/query/{id}的api,参数id在某些情况下可能是uuid,在其他情况下可能是long值。 除了添加越来越多的正则表达式模式之外,还有其他更好的方法吗?gateway的总体目标是尽可能减少时间。无论如何,我还是想出了一个合适的解决方案。所有项目中的@PathVariable位于URL的最后或最后两部分。e、

我正在尝试在网关上编写api权限筛选器。应该禁止不带有特定角色的令牌访问资源。除了包含
@PathVariable
参数的API之外,所有请求都已被有效过滤。例如,URI为
/api/v1/query/{id}
的api,参数
id
在某些情况下可能是
uuid
,在其他情况下可能是
long
值。
除了添加越来越多的正则表达式模式之外,还有其他更好的方法吗?gateway的总体目标是尽可能减少时间。

无论如何,我还是想出了一个合适的解决方案。所有项目中的
@PathVariable
位于URL的最后或最后两部分。e、 g.
/api/v1/data/query/{uid}/{pid}
或类似的东西。因此,我们可以使用Apache Common的
StringUtils#lastIndexOf()
StringUtils#substring()
消除该部分

要编写演示代码,请同时导入Hutool和Commons-Lang3


胡图尔
胡图尔
5.5.8
org.apache.commons
commons-lang3
3.11
导入cn.hutool.core.util.IdUtil;
导入org.apache.commons.lang3.StringUtils;
公共类StringDemo{
公共静态void main(字符串[]args){
字符串url=”http://localhost:8080/api/v1/data/query/“+IdUtil.simpleuid()+”/“+IdUtil.getSnowflake(1L,16.nextId();
System.out.println(url);
int index=StringUtils.lastIndexOf(url,“/”);
stringsuburl=StringUtils.substring(url,0,索引);
System.out.println(子URL);
int index2=StringUtils.lastIndexOf(子URL,“/”);
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简化为最简单的uri(在我的例子中是
/api/v1/data/query
),可以轻松编写相关代码来检查角色。

您可以向
FormatterRegistry
提供自己的
转换器。请检查:@PranjalGore在我的情况下不起作用,因为我正在编写的代码将在API网关上运行,并且过滤的API列表不在同一个项目中。