項目簡介:
1,按照項目1的案例搭建一個SpringMVC的框架。(項目一:http://blog.csdn.net/escore/article/details/49490625)
2,我們創建一個新的java類
在類中第一個方法我們直接返回的是ModelAndView,其它三個方法我們是返回字符串,並在方法的入參中分別注入了Map、Model、ModelMap。
也就是說以上四種方式都可以將模型數據傳遞出去。
只是ModelAndView對象將View(視圖)和模型數據(Model)結合在一起返回了,而其他三種則是分開的(四個方法中的“success”相當於視圖View)。
通過這四種方式將模型數據傳遞到了request域中。
注:需要了解的是實際上SpringMVC最後都會將所有的模型數據轉換爲ModelAndView,不管你是Map、Model等等,或者你沒有返回模型數據值返回了“success”(相當於視圖)SpringMVC也會將其轉換成一個ModelAndView對象,後面將結合視圖、視圖解析器詳細講解。
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@RequestMapping("/testViewAndModel")
@Controller
public class TestViewAndModel {
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView() {
ModelAndView mv = new ModelAndView();
mv.setViewName("success");
String[] names = { "zz", "xx", "cc" };
mv.addObject("names", names);
return mv;
}
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map) {
map.put("name", "maptest");
return "success";
}
@RequestMapping("/testModel")
public String testModel(Model model) {
model.addAttribute("address", "changsha");
return "success";
}
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap) {
modelMap.addAttribute("modelMap", "modelMap");
return "success";
}
}
3,在index.jsp頁面中添加如下代碼。
<body>
<a href="testViewAndModel/testModelAndView">testModelAndView</a><br>
<a href="testViewAndModel/testMap">testMap</a><br>
<a href="testViewAndModel/testModel">testModel</a><br>
<a href="testViewAndModel/testModelMap">testModelMap</a><br>
</body>
4,在views文件中success中添加如下代碼。
<body>
<h1>Success Page</h1><br>
names: ${requestScope.names }<br>
name : ${requestScope.name }<br>
address: ${requestScope.address }<br>
address: ${requestScope.modelMap }<br>
</body>
5,運行流程。
在編寫代碼後我們通過訪問index.jsp頁面的地址,然後在通過RequestMapping註解的方法,最後轉到success.jsp頁面獲得我們在後臺獲得的數據。