路径段序列到JAX-RS / Jersey中的vararg数组? [英] Path segment sequence to vararg array in 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.
有没有办法将未知数量的路径元素转换为vararg Java方法的参数? I. e。 / foo / bar / x / y / z
应该转到方法: foo(@PathParam(...)String [] params){。 ..}
其中 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
我可以在泽西岛/ 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.
查看 docs 。
最后,作为使用@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中的vararg数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!