Search code examples
jersey

Option path parameters returning 404 in Jersey


I'm trying to use a path like this, with the last parameter optional, so that if it's present it's used, otherwise it's simply set to null or empty.

@Path("/create/{param1}{param2:(/param2/[^/]+?)?}")

However I get a 200 when the first static parameter is set, but i get a 404 (not found) when the second option parameter is set as well.

For example, this fails with a 404:

http://hostname/create/abc1/abc2

and this succeeds with a 200:

http://hostname/create/abc1

What am I doing wrong with that optional path that Jersey can't match it?


Solution

  • Although I'm sure there are solutions to this issue, I resolved it by overloading the method so that a single param is sent to one receiving method and both params are sent to another. They then both hand off to a handler method so we reduce code duplication. This works using simple java overloading and removes the need for complicated matching syntax, which will make later maintenance easier.

    @PUT
    @Path("/create/{param1}")
    public Response doThingMethod(@PathParam("param1") String param1){
        return passToHandler(param1, null)
    }
    
    @PUT
    @Path("/create/{param1}/{param2}")
    public Response doThingMethod(@PathParam("param1") String param1, @PathParam("param2") String param2){
        return passToHandler(param1, param2)
    }
    

    Hopefully, that helps someone else having the same issue.