【SpringMVC】返回視圖中包含數據(ModelAndView)


在普通的servlet項目中,Controller獲取了數據,需要在視圖顯示,需要顯示的調用request.setAttribute()等方法

在SpringMVC中,使用ModelAndView、ModelMap,Model,Map。

以下四種方式都是放在request域中,

如果放在Session中,在類名前加上@SessionAttributes("student"),@SessionAttributes("student1")這樣的注解,注解中為放入request域中名字(如果需要在session中放入所有Student類型的對象,@SessionAttributes(types=Student.class)或@SessionAttributes(types= {Student.class,Adress.class}))

ModelAndView示例 方法:

    public ModelAndView testModelAndView(){
        // Model:M View:V
        ModelAndView modelAndView = new ModelAndView("success");
        Student student = new Student();
        student.setId(1);
        student.setName("zs");
        // equals to : request.setAttribute("student",student);
        modelAndView.addObject("student",student);
        return modelAndView;

    }

訪問鏈接:

<a href="handler/testModelAndView">testModelAndView</a>

放在request域中,頁面輸出:${requestScope.student.id}

 

ModelMap方式:

    @RequestMapping(value = "testModelMap")
    public String testModelMap(ModelMap modelMap) {
        Student student = new Student();
        student.setId(123);
        student.setName("qwer");
        modelMap.put("student2", student);
        return "success";
    }

 

Map方式:

    @RequestMapping("testMap")
    public String testMap(Map<String, Object> map) {
        Student student = new Student();
        student.setId(2);
        student.setName("asd");
        map.put("student3", student);
        return "success";
    }

 

Model方式:

    @RequestMapping("testModel")
    public String testModel(Model model) {
        Student student = new Student();
        student.setId(3);
        student.setName("ttt");

        model.addAttribute("student3", student);
        return "success";
    }

 


免責聲明!

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



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