I am doing a Spring web. For a controller method, I am able to use RequestParam to indicate whether a parameter it is required or not. For example:
@RequestMapping({"customer"}) public String surveys(HttpServletRequest request, @RequestParam(value="id", required = false) Long id, Map<String, Object> map)
I would like to use PathVariable such as the following:
@RequestMapping({"customer/{id}"}) public String surveys(HttpServletRequest request, @PathVariable("id") Long id, Map<String, Object> map)
How can I indicate whether a path variable is required or not? I need to make it optional because when creating a new object, there is no associated ID available until it is saved.
Thanks for help!
Using @PathVariable required attribute From Spring 4.3. 3 version, @PathVariable annotation has required attribute, to specify it is mandatorily required in URI. The default value for this attribute is true if we make this attribute value to false, then Spring MVC will not throw an exception.
@PathVariable Optional using required false If the request url is invoked, the rest controller will execute a method without the value of the path attribute. But the @PathVariable annotation is requiring a value to be configured. @PathVariable should be made as an optional using required=false.
Another way to define an optional path variable that is available since Spring 3.2 is with a Map for @PathVariable parameters: @RequestMapping(value = {"/article", "/article/{id}"}) public Article getArticle(@PathVariable Map<String, String> pathVarsMap) { String articleId = pathVarsMap. get("id"); if (articleId !=
VTTom`s solution is right, just change "value" variable to array and list all url possibilities: value={"/", "/{id}"}
@RequestMapping(method=GET, value={"/", "/{id}"}) public void get(@PathVariable Optional<Integer> id) { if (id.isPresent()) { id.get() //returns the id } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With