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

curious1 picture curious1 · Jul 23, 2013 · Viewed 62.2k times · Source

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!

Answer

Martin Cmarko picture Martin Cmarko · Dec 18, 2015

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
  }
}