optional POST parameter in spring MVC?

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));
    ...
}

Leave a Comment

techhipbettruvabetnorabahisbahis forumu