Passing model data to the view

As of now, we have implemented a very simple HomeCotroller, and tested it. But in the web application, we have also passed model data to the view layer. That model data we passed in the model (in a simple word, it is Map), and that model is returned by the controller along with logical view name. As you already know, Spring MVC supports several return types of the handler method. Let's see the following example:

    package com.packt.patterninspring.chapter10.bankapp.web.controller; 
 
    import java.util.List; 
 
    import org.springframework.beans.factory.annotation.Autowired; 
    import org.springframework.stereotype.Controller; 
    import org.springframework.ui.ModelMap; 
    import org.springframework.web.bind.annotation.GetMapping; 
    import org.springframework.web.bind.annotation.PostMapping; 
 
    import com.packt.patterninspring.chapter10.bankapp.model.Account; 
    import com.packt.patterninspring.chapter10.bankapp.service.AccountService; 
 
    @Controller 
    public class AccountController { 
    
     @Autowired 
     AccountService accountService; 
    
     @GetMapping(value = "/open-account") 
     public String openAccountForm (){ 
         return "account"; 
     } 
    
     @PostMapping(value = "/open-account") 
     public String save (Account account, ModelMap model){ 
         account = accountService.open(account); 
         model.put("account", account); 
         return "accountDetails"; 
     } 
    
     @GetMapping(value = "/all-accounts") 
     public String all (ModelMap model){ 
         List<Account> accounts = accountService.findAllAccounts(); 
         model.put("accounts", accounts); 
         return "accounts"; 
     } 
   } 

As you can see in the preceding example, the AccountController class has three handler methods. Two handler methods return the model data along with the logical view name. But in this example, I am using Spring MVC's ModelMap, so, we don't need to forcefully return as logical view, it binds automatically with the response.

Next you'll learn how to accept request parameters.

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

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