How to make @RequestParam Optional

5 years ago by in How To, Spring, Web Application Tagged: , , , ,

A @RequestParam (Java Doc) can be set as optional, by simply providing a default value to it as shown in the following example

@Controller
public class MyController {

  @RequestMapping(value = "/myApp", method = { RequestMethod.POST, RequestMethod.GET })
  public String doSomething(@RequestParam(value = "name", defaultValue = "anonymous") final String name) {
  // Do something with the variable: name
  return "viewName";
  }

}
Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 SearchSecurity.co.UK award (Website).

One Response to “How to make @RequestParam Optional”


Nasreen
February 9, 2015 Reply

You can make the @requestparam optional by making the attribute "required=false" as shown below.

  @RequestMapping(value = "/myApp", method = { RequestMethod.POST, RequestMethod.GET })
  public String doSomething(@RequestParam(value = "name", required=false) final String name) {
    // Do something with the variable: name
    return "viewName";
  }

Leave a Comment


Time limit is exhausted. Please reload the CAPTCHA.