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 中可变参数数组的路径段序列?
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
