Optional @PathParam in Jax-RS

2019-01-14 10:36发布

问题:

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?

回答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.



回答2:

In my case I had to use this other expression:

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

Otherwise you have to clean the parameter.



回答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.



回答4:

With Dropwizard 1.0 and Java8 you can use Optional

@Path("/news")
getLastNews(@QueryParam("topicId") String topicId, @QueryParam("limit") Optional<Integer> limit) 

It will give a response to both

/news?topicId=123213?limit=200

and

/news?topicId=123213