Path segment sequence to vararg array in JAX-RS / Jersey?

假如想象 提交于 2019-12-30 07:03:12

问题


JAX-RS/Jersey allows URL path elements to be converted to Java method arguments using @PathParam annotations.

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

Can I do this in Jersey/JAX-RS or some convenient way?


回答1:


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();
   ...
}

Where VariableStrings is a class that you define.

public class VariableStrings {

   private String[] splitPath;

   public VariableStrings(String unparsedPath) {
     splitPath = unparsedPath.split("/");
   }
}

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.

Check out the docs.

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 gives a good overview.



来源:https://stackoverflow.com/questions/10925135/path-segment-sequence-to-vararg-array-in-jax-rs-jersey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!