How to use Spring RequestParam with examples

The RequestPrams is an annotation provided in Spring MVC framework to make extracting data from HTTP request easier. The mechanism makes the code more declarative, reduces a lot of boilerplate code.

It allows you bound a controller method parameter to a HTTP request GET parameter. Here is an example, send a AJAX request to page foo with a GET parameter:

 
  <script type="text/javascript">
    function sendRequest() {
      $.ajax({
        url: 'foo.html',
        data: ({name : "sam"}),
        success: function(data) {
          $('#greeting').html(data);
        }
      });
    }
  </script>
 

The Spring controller goes like

 
  @RequestMapping(value = "/foo", method = RequestMethod.GET)
  public @ResponseBody String getGreeting(@RequestParam String name) {
    String result = "Hello! " + name ; 
    return result;
  }
 

Make @RequestParam optional

Spring also support optional parameter, that is, gives the parameter a default value if its not present.

 
  @RequestMapping(value = "/foo", method = RequestMethod.GET)
  public @ResponseBody String getGreeting( @RequestParam(value = "name", defaultValue = "stranger") String name) {
    String result = "Hello! " + name ; 
    return result;
  }