Take the 2-minute tour ×

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!


share|improve this question

2 Answers 2

up vote 14 down vote accepted

Instead of using @RequestParam for the optional paramaters, 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
    // optional parameter is not there.

Note: See below (defaultValue and required) for a way to solve this without using a WebRequest parameter.

share|improve this answer
Down-voted and accepted? :-D –  Petro Semeniuk Jul 4 '12 at 1:40
It seems, not always good to be correct. :P –  DwB Jul 4 '12 at 14:09
I upvoted it so it more/less fair ;-) –  Petro Semeniuk Jul 7 '12 at 5:42
better solution below! –  Akin Okegbile Nov 14 '13 at 21:11
different solution below (required = false) –  DwB Nov 15 '13 at 14:17

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.

share|improve this answer
I think this method is much cleaner than including the WebRequestParameter. –  Jay May 7 '12 at 20:49
Also note that if your request parameter is a primitive (like int) and you mark it as required=false, you will want to use a wrapper class (like Integer) instead so that it can be passed as a null value to the controller method if the request parameter was not present. –  Jay May 7 '12 at 20:50
This can be used for @RequestHeader as well! –  CK Lee Aug 26 '13 at 9:28
The 'value = ' part is optional. –  Hoffmann Oct 31 '13 at 15:50

Your Answer


