Path segment sequence to vararg array in JAX-RS / Jersey?(JAX-RS/Jersey 中可变参数数组的路径段序列?)
问题描述
JAX-RS/Jersey 允许使用 @PathParam
注释将 URL 路径元素转换为 Java 方法参数.
JAX-RS/Jersey allows URL path elements to be converted to Java method arguments using @PathParam
annotations.
有没有办法将未知数量的路径元素转换为可变参数 Java 方法的参数?/foo/bar/x/y/z
应该去方法: foo(@PathParam(...) String [] params) { ... }
where params[0]
是 x
,params[1]
是 y
和 params[2]
是 z
Is there a way to convert an unknown number of path elements into arguments to a vararg Java method? I. e. /foo/bar/x/y/z
should go to method: foo(@PathParam(...) String [] params) { ... }
where params[0]
is x
, params[1]
is y
and params[2]
is z
我可以使用 Jersey/JAX-RS 或其他方便的方式来执行此操作吗?
推荐答案
不确定这是否正是您要寻找的,但您可以这样做.
Not sure if this is exactly what you were looking for but you could do something like this.
@Path("/foo/bar/{other: .*}
public Response foo(@PathParam("other") VariableStrings vstrings) {
String[] splitPath = vstrings.getSplitPath();
...
}
VariableStrings 是您定义的类.
Where VariableStrings is a class that you define.
public class VariableStrings {
private String[] splitPath;
public VariableStrings(String unparsedPath) {
splitPath = unparsedPath.split("/");
}
}
注意,我没有检查过这段代码,因为它只是为了给你一个想法.这是有效的,因为 VariableStrings 可以由于它们的构造函数而被注入只需要一个字符串.
Note, I haven't checked this code, as it's only intended to give you an idea. This works because VariableStrings can be injected due to their constructor which only takes a String.
查看 文档.
最后,作为使用@PathParam 注解注入VariableString 的替代方法您可以改为将此逻辑包装到您自己的自定义 Jersey Provider 中.该提供程序将注入一个VariableStrings"或多或少与上面相同的方式,但它可能看起来更干净一些.不需要 PathParam 注释.
Finally, as an alternative to using the @PathParam annotation to inject a VariableString you could instead wrap this logic into your own custom Jersey Provider. This provider would inject a "VariableStrings" more or less the same manner as above, but it might look a bit cleaner. No need for a PathParam annotation.
Coda Hale 给出了一个很好的概述.
Coda Hale gives a good overview.
这篇关于JAX-RS/Jersey 中可变参数数组的路径段序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JAX-RS/Jersey 中可变参数数组的路径段序列?
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01