I have the following code:
@RequestMapping(method = RequestMethod.POST) public ModelAndView editItem(String name, String description)
However, sometime description is not passed in (this is a simplified example than the real one), and i would like to make description optional, perhaps by filling in a default value if none is passed in.
Anyone have any idea how to do that?
thanks a lot!
Jason
You can do it in three ways: Set required = false in @RequestParam annotation. Set defaultValue = “any default value” in @RequestParam annotation. Using Optional keyword.
Usecase when need optional @PathVariable E.g. we may have a method in Spring MVC controller which can be used to create a new record or edit an existing record – based on the presence of 'id' attribute of record.
As query parameters are not a fixed part of a path, they can be optional and can have default values.
Method parameters annotated with @RequestParam are required by default. will correctly invoke the method. When the parameter isn't specified, the method parameter is bound to null.
If you are using Spring MVC 3.0 or higher then just set defaultValue
parameter of @RequestParam
:
public ModelAndView editItem(@RequestParam(value = "description", defaultValue = "new value") String description)
In Spring MVC 2.5, I suggest to mark value as required = false
and check their value against null manually:
public ModelAndView editItem(@RequestParam(value = "description", required = false) String description) { if (description == null) { description = "new value"; } ... }
See also corresponding documentation about @RequestParam annotation.
UPDATE for JDK 8 & Spring 4.1+: now you could use java.util.Optional
like this:
public ModelAndView editItem(@RequestParam("description") Optional<String> description) { item.setDescription(description.getOrElse("default value")); // or only if it's present: description.ifPresent(value -> item.setDescription(description)); ... }
Instead of using @RequestParam
for the optional parameters, take a parameter of type org.springframework.web.context.request.WebRequest
. For example,
@RequestMapping(method = RequestMethod.POST) public ModelAndView editItem( @RequestParam("name")String name, org.springframework.web.context.request.WebRequest webRequest) { String description = webRequest.getParameter("description"); if (description != null) { // optional parameter is present } else { // optional parameter is not there. } }
Note: See below (defaultValue and required) for a way to solve this without using a WebRequest parameter.
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