我正在尝试使用 Java 捕获 AkkaHTTP 中 URL 路径的每个片段。
这是我的代码:
public Route routes() {
return route(pathPrefix("users", () ->
route(
getOrPostUsers(),
path(PathMatchers.segment(), name -> route(
getUser(name),
deleteUser(name),
path(PathMatchers.segment(), countryOfResidence -> route(
getUser(name, countryOfResidence),
deleteUser(name, countryOfResidence)
))
)
)
)
));
}
因此,如您所见,我试图获取 URL 路径的第一段并将其存储为 name
和 URL 路径的第二段并将其存储为 居住国家
。一个示例 URL 类似于
localhost:8080/users/ian/usa
如果用户仅输入localhost:8080/users/ian
,我想路由到函数getUser()或deleteUser()的版本,具体取决于HTTP请求的类型,即只接受一个名字。如果用户输入更长的 URL,如上所述,我想调用带有两个参数的 getUser() 或 deleteUser() 版本。
每当我运行上面的代码时,名称的 PathMatcher 都工作得很好。当我运行名称和国家/地区的 PathMatcher 时,会出现问题。这些路由中的代码永远不会运行,并且服务器不会返回任何 JSON。
最佳答案
我认为问题在于指令是按顺序尝试的,因此较短的指令将在尝试更具体的指令之前匹配。我建议您尝试以下任一方法:
将最具体的路径放在前面 (
path(PathMatchers.segment(), countryOfResidence ...
),以便它可以在较短的路径匹配之前进行匹配,或者使用指令为较短的情况添加后缀以匹配 pathEndOrSingleSlash(),以便它们明确不会匹配较长的路径:
path(PathMatchers.segment(), name -> route( pathEndOrSingleSlash(() -> route( getUser(name), deleteUser(name) ), path(PathMatchers.segment(), countryOfResidence -> route( getUser(name, countryOfResidence), deleteUser(name, countryOfResidence) )) ) )
关于java - 捕获Akka/Java中路径的所有段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50307287/