Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC: how to indicate whether a path variable is required or not?

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!

like image 320
curious1 Avatar asked Jul 23 '13 21:07

curious1


People also ask

Is path variable required?

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.

How do you make a path variable required?

@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.

How do you make a path variable optional in Spring?

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 !=


1 Answers

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   } } 
like image 144
Martin Cmarko Avatar answered Nov 04 '22 08:11

Martin Cmarko