SpringMVC之ModelAndView


一、SpringMVC輸出模型數據的幾種常見途徑

  1、ModelAndView

@Controller
public class SpringmvcDemo {

    @RequestMapping(value = "/testModelAndView", method = RequestMethod.GET)
    public ModelAndView testSpringMVC() {
        // 使用ModelAndView的方式
        ModelAndView mav = new ModelAndView();
        mav.addObject("username", "damaomao");
        mav.setViewName("testModelAndView");
        System.out.println("測試ModelAndView");
        return mav;
    }
}

  2、Map<Object,Object>集合

@Controller
public class SpringmvcDemo {

    @RequestMapping(value = "/testModelAndView", method = RequestMethod.GET)
    // 使用返回值是String類型,參數為map
    public String testSpringMVC01(Map<String,Object> map) {
        map.put("user01","xiaomao");
        map.put("user02","xiaomaomao");
        map.put("user03","xiaoxiaomaomao");
        return "testModelAndView";
    }
}

  3、Model對象

@Controller
public class SpringmvcDemo {

    @RequestMapping(value = "/testModelAndView", method = RequestMethod.GET)
    // 使用返回值是String類型,參數為Model
    public String testSpringMVC01(Model model) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("user01","haha");
        hashMap.put("user02","hehe");
        hashMap.put("user03","heihei");
        model.addAllAttributes(hashMap);
        return "testModelAndView";
    }
}

  

二、處理Model源碼參考

  通過上面源碼看出使用上述幾種輸出模型本質上都是Servlet中的request.getDispatcher.forward(request,response)的方式往域對象中存儲值.

 

三、處理View源碼參考

  1、一般情況下,控制器方法返回字符串類型的值會被當成邏輯視圖名處理

  2、如果返回的字符串中帶forward:或redirect:前綴時,SpringMVC 會對他們進行特殊處理:將 forward: 和redirect: 當成指示符,其后的字符串作為URL來處理

    例如:

      redirect:success.jsp:會完成一個到 success.jsp 的重定向的操作

      forward:success.jsp:會完成一個到 success.jsp 的轉發操作

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM