Taking query parameters

In a web application, we can fetch the request parameters from the request-the account ID in our example if you want to access the details of a particular account. Let's fetch the account ID from the request parameter using the following code:

    @Controller 
    public class AccountController { 
      @GetMapping(value = "/account") 
      public String getAccountDetails (ModelMap model, HttpServletRequest request){ 
         String accountId = request.getParameter("accountId"); 
         Account account = accountService.findOne(Long.valueOf(accountId)); 
         model.put("account", account); 
         return "accountDetails"; 
     } 
    }  

In the preceding code snippet, I have used the traditional way to access the request parameters. The Spring MVC framework provides an annotation, @RequestParam, to access the request parameters. Let's use the @RequestParam annotation to bind the request parameters to a method parameter in your controller. The following code snippet shows the usage of the @RequestParam annotation. It extracts the parameter from the request, and performs type conversion as well:

    @Controller 
    public class AccountController { 
     @GetMapping(value = "/account") 
     public String getAccountDetails (ModelMap model, @RequestParam("accountId") long accountId){ 
         Account account = accountService.findOne(accountId); 
         model.put("account", account); 
         return "accountDetails "; 
    } 
   }  

In the preceding code, we access the request parameter by using the @RequestParam annotation, and you can also notice that I didn't use the type conversion from String to Long, it will be done automatically by this annotation. One more thing to note here is that parameters using this annotation are required by default, but Spring allows you to override this behavior by using the required attribute of the @RequestParam annotation.

    @Controller 
    public class AccountController { 
      @GetMapping(value = "/account") 
      public String getAccountDetails (ModelMap model,  
         @RequestParam(name = "accountId") long accountId 
         @RequestParam(name = "name", required=false) String name){ 
         Account account = accountService.findOne(accountId); 
         model.put("account", account); 
         return " accountDetails "; 
     } 
   } 

Now let's see how to use path variables to take input as part of the request path.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset