首页 > 解决方案 > 如何知道 URL 是否与特定的 PATH 匹配

问题描述

我正在尝试在 Java 过滤器中执行一些逻辑,具体取决于请求 URL 是否与特定 PATH 匹配。我们想使用 Java 的 PathMatcher 之类的东西,而不是 Regex。另外要求,明确声明不使用 Spring,因此 spring 的 PathMatcher 不是一个选项。

例如给出以下 URL:
http://localhost:8080/base_path/customer/ {PARAM_VAL1}/order/{PARAM_VAL2}

我正在寻找某种方式使 IF 产生真实:

PathMatcher pm = new SomeURLPathMatcherImp("/base_path/customer/*/order/*");

myURI = "/base_path/customer/customer001/order/98536"

if ( pm. matches(myURI) ){
    myFunction();
}

注意:我使用 PathMatcher 来描述问题。我想知道除了 Spring 之外是否有任何 API 库来执行类似于 Java 的 FileSystem 类实现的 URL PATH 匹配

标签: javaurlpath

解决方案


PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:/base_path/customer/*/order/*");

System.out.println(pm.matches(Paths.get("/base_path/customer/customer001/order/98536")));  // true
System.out.println(pm.matches(Paths.get("/base_path/customer/customer001/order")));        // false

推荐阅读