天天看點

SpringMVC學習筆記(六)模型資料處理(一)SpringMVC學習筆記(六)

SpringMVC學習筆記(六)

文章目錄

  • SpringMVC學習筆記(六)
    • 1.使用ModelAndView處理資料
    • 2.使用Map、ModelMap、Model作為方法來處理資料

   SpringMVC提供了幾種種途徑來處理帶資料的視圖,分别是:ModelAndView、Map、ModelMap及Model,@SessionAtrributes,@ModelAttribute。下面我們分别來具體介紹:

1.使用ModelAndView處理資料

 請求頁面:

 控制器controller:

//使用ModelAndView類型的參數
	@RequestMapping(value="/testModelAndView")
	public ModelAndView testModelAndView() {
		String view="modelSuccess";
		ModelAndView m=new ModelAndView(view);
		Student student=new Student();
		student.setsName("張小蟀1");
		//添加student對象資料放入ModelAndView中
		m.addObject("student",student);
		return m;
	}
           

 響應頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>成功界面</title>
</head>
<body>
 
request作用域中:${requestScope.student.sName}<br/>
session作用域中:${sessionScope.student.sName}
 
</body>
</html>
           

 運作結果:

SpringMVC學習筆記(六)模型資料處理(一)SpringMVC學習筆記(六)

   ModelAndView的構造方法将視圖頁面的名稱modelSuccess放入定義的m對象中,在通過addOBbject()方法将輸入放入m對象,最後傳回mv,程式會吧m中的資料student放入request作用域中。

2.使用Map、ModelMap、Model作為方法來處理資料

 請求頁面:

<a href="model/testMap">超連結測試2:testMap</a><br/>
	<a href="model/testModelMap">超連結測試3:testModelMap</a><br/>
	<a href="model/testModel">超連結測試4:testModel</a><br/>
           

 控制器controller:

//使用Map類型的參數
	@RequestMapping(value="/testMap")
	public String testMap(Map<String,Object> map) {
		Student student=new Student();
		student.setsName("張小蟀2");
		map.put("student", student);
		return "modelSuccess";
	}
	//使用ModelMap類型的參數
	@RequestMapping(value="/testModelMap")
	public String testModelMap(ModelMap map) {
		Student student=new Student();
		student.setsName("張小蟀3");
		map.put("student", student);
		return "modelSuccess";
	}
	//使用Model類型的參數
	@RequestMapping(value="/testModel")
	public String testModel(Model map) {
		Student student=new Student();
		student.setsName("張小蟀4");
		map.addAttribute("student", student);
		return "modelSuccess";
	}
           

 請求頁面還是和上面ModelAndView的一樣:

 運作結果:

SpringMVC學習筆記(六)模型資料處理(一)SpringMVC學習筆記(六)

  給SpringMVC的請求方法增加一個Map、ModelMap、Model類型的參數,向Map、ModelMap、Model中增加資料,該資料也會放入request作用域中。