necromancer
necromancer

Reputation: 24651

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

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?

Upvotes: 5

Views: 4015

Answers (1)

esiegel
esiegel

Reputation: 1783

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.

Upvotes: 4

Related Questions