【问题标题】:How to judge if a @PathVariable exists in request URL?如何判断请求URL中是否存在@PathVariable?
【发布时间】:2021-05-07 10:26:37
【问题描述】:

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

【问题讨论】:

  • 您可以将自己的Converter 提供给FormatterRegistry。看看这个:baeldung.com/spring-mvc-custom-data-binder
  • @PranjalGore 这在我的情况下不起作用,因为我正在编写的代码将在 API 网关上运行,并且过滤后的 Api 列表不在同一个项目中。

标签: spring spring-boot api-gateway


【解决方案1】:

无论如何,我想出了一个合适的解决方案。所有项目中的@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,很容易编写相关代码来检查角色。

【讨论】:

    猜你喜欢
    • 2014-12-24
    • 2013-02-21
    • 2010-10-15
    • 2017-12-12
    • 2015-09-21
    • 2019-03-29
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    相关资源
    最近更新 更多