JAX-RS/Jersey 中可变参数数组的路径段序列?

Path segment sequence to vararg array in JAX-RS / Jersey?(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]xparams[1]yparams[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 中可变参数数组的路径段序列?

基础教程推荐