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 中可变参数数组的路径段序列?
基础教程推荐
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01