One of the neat things you can do in Spring 3 MVC is to map request parameters into specific controller method input arguments. This is done by applying the @RequestParam annotation to your controller method signature:

  @RequestMapping(value = "/help/detail", method = RequestMethod.GET)
  
public String displaySomeHelpDetail(@RequestParam("uuid"String uuid, Model model) {
    
return "view.name";
  
}

In the above example, the @RequestMapping annotation routes all GET requests with the URL /help/detail to your method. Using@RequestParam(“uuid”) means that Spring will then grab the uuid value from the request string and attach it to the String uuidmethod argument. Knowing this, you can see that the method above will process all GET requests with the following format:/help/detail?uuid=SomeValue, where SomeValue becomes the uuid argument.

In the above, the uuid is part of the @RequestParam’s value attribute and hence, the method signature could have been written as:

  @RequestMapping(value = "/help/detail", method = RequestMethod.GET)
  
public String displayMyFirstHelpDetail(@RequestParam(value="uuid"String uuid, Model model) {
    
return "view.name";
  
}

Indeed, @RequestParam has two other optional attributes: required and defaultValuerequired is a boolean that’s applied to the value attribute that defaults to true. When true, then a exception is thrown if the request parameter is missing from the URL request string. When required is false, then an exception is not thrown and the input argument is set to null. An example of how to use required is:

  @RequestMapping(value = "/help/detail", method = RequestMethod.GET)
  
public String displaySomeOtherHelpDetail(@RequestParam(value="uuid", required=falseString uuid, Model model) {
    
return "view.name";
  
}

In the above code, a request URL string of /help/detail?uuid=SomeValue will ensure that uuid is set to SomeValue. When the request param is missing and the URL request string is: /help/detail, then the uuid method argument will be set to null.

Using defaultValue automatically sets required to false, and inserts a ‘default value’ into your input argument when the request parameter is missing from your URL. An example of how to use defaultValue is:

  @RequestMapping(value = "/help/detail", method = RequestMethod.GET)
  
public String displayYetOtherHelpDetail(@RequestParam(value="uuid", defaultValue="hello"String uuid, Model model) {
    
return "view.name";
  

In the above code, a request URL string of /help/detail?uuid=SomeValue will ensure that uuid is set to SomeValue. When the request param is missing and the URL request string is: /help/detail, then the uuid method argument will be set to: hello.

0 comments :

Post a Comment

 
Top