5

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?

necromancer
  • 23,916
  • 22
  • 68
  • 115

1 Answers1

4

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.

esiegel
  • 1,773
  • 2
  • 19
  • 31
  • elegant workaround; and in particular, great idea to have a reusable class to do the parsing. i'll accept this after some time to confirm that there is no direct way. thanks! – necromancer Jun 07 '12 at 17:18
  • Another thing you could do, which is more or less the same thing, is wrap this logic in your own custom Jersey Provider. This provider would inject a "VariableStrings" object for you. No need for a PathParam annotation. – esiegel Jun 07 '12 at 22:23
  • 1
    Coda Hale gives a good overview. http://codahale.com/what-makes-jersey-interesting-injection-providers/ – esiegel Jun 07 '12 at 22:29
  • thanks for that additional bit -- could you please edit that last bit into the main answer and i'll accept it as the correct one. thanks! – necromancer Jun 07 '12 at 23:25
  • I added the comment above as requested. – esiegel Jun 09 '12 at 17:49
  • thanks very much! (it will help whoever has the same question next time) :) – necromancer Jun 10 '12 at 05:12
  • For another possible solution, see [http://stackoverflow.com/questions/8903907](http://stackoverflow.com/questions/8903907), which shows this done using `List` rather than a custom class – Forge_7 Mar 01 '16 at 16:44