With Spring 3.0, can I have an optional path variable?
For example
@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(
HttpServletRequest req,
@PathVariable String type,
@RequestParam("track") String track) {
return new TestBean();
}
Here I would like /json/abc
or /json
to call the same method.
One obvious workaround declare type
as a request parameter:
@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testAjax(
HttpServletRequest req,
@RequestParam(value = "type", required = false) String type,
@RequestParam("track") String track) {
return new TestBean();
}
and then /json?type=abc&track=aa
or /json?track=rr
will work
You can't have optional path variables, but you can have two controller methods which call the same service code:
It's not well known that you can also inject a Map of the path variables using the @PathVariable annotation. I'm not sure if this feature is available in Spring 3.0 or if it was added later, but here is another way to solve the example:
Spring 5 / Spring Boot 2 examples:
blocking
reactive
Check this Spring 3 WebMVC - Optional Path Variables. It shows an article of making an extension to AntPathMatcher to enable optional path variables and might be of help. All credits to Sebastian Herold for posting the article.
If you are using Spring 4.1 and Java 8 you can use
java.util.Optional
which is supported in@RequestParam
,@PathVariable
,@RequestHeader
and@MatrixVariable
in Spring MVC -