Search code examples
springspring-mvcpath-variables

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!


Solution

  • There's no way to make it optional, but you can create two methods with one having the @RequestMapping({"customer"}) annotation and the other having @RequestMapping({"customer/{id}"}) and then act accordingly in each.