Optional @PathParam in Jax-RS

45,558

Solution 1

The problem was the lack of whitespace before the colon:

@Path("/mypath{param1: (/param1)?}")

should be:

@Path("/mypath{param1 : (/param1)?}")

Apparently it's a bug, because the specification makes the whitespace around the colon optional. I also found that I'm not the first bitten by this bug.

Solution 2

In my case I had to use this other expression:

@Path('/mypath/{param1 : (\\w+)?}')

Otherwise you have to clean the parameter.

Solution 3

Verify whether there is a path already defined with /mypath that accepts a different method, this could be the reason why you are getting 405 (Method not allowed) back. Also when you have optional parameters I guess it is better to make them query parameters.

Share:
45,558

Related videos on Youtube

Shane Larson
Author by

Shane Larson

Living in southern Brazil.

Updated on July 22, 2020

Comments

  • Shane Larson
    Shane Larson almost 4 years

    I have a service where the last part of the path is optional, the user can both enter /mypath/ and /mypath/param1/.

    I tried to use a regular expression to filter the last part of the path:

    @Path("/mypath{param1: (/param1)?}")

    I'm using RestEasy as my JAX-RS provider and the code works as expected in Tomcat but when I deploy it in JBoss I get a 405 return code when I do not submit the optional part.

    Am I doing something wrong here or it's not possible to accomplish this in a portable way?

  • Neeraj Jain
    Neeraj Jain over 8 years
    Not working in my case but this does
  • Zarathustra
    Zarathustra over 7 years
    It is about @Path not @QueryParam
  • Shane Larson
    Shane Larson about 5 years
    @NeerajJain my question involves RestEasy, the one you linked is about Jersey.
  • QuirkyBit
    QuirkyBit about 3 years
    This was the error that I was getting. I had a GET at / and a POST at /{filename} where filename was optional. So the post at GET and POST were clashing.
  • AlikElzin-kilaka
    AlikElzin-kilaka about 2 years
    The value of param1 includes the slash (/). Without manually cutting the slash in the code, is there a way to not include the slash in the value?