Reputation: 15176
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
Upvotes: 33
Views: 51101
Reputation: 15214
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));
...
}
Upvotes: 128
Reputation: 38328
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.
Upvotes: 19