springmvc006 - Processing model data

Posted by katarra on Wed, 17 Jun 2020 02:51:56 +0200

Project Profile:


1. Build a framework for SpringMVC based on Project 1's case.(Item 1: http://blog.csdn.net/escore/article/details/49490625)

2, we create a new java class

The first method in the class returns ModelAndView directly, while the other three methods return strings and inject Map, Model, ModelMap into the method's arguments.

That is, the model data can be transferred in all four ways.

Only the ModelAndView object returns the View with the model data, while the other three are separate (the "success" in the four methods is equivalent to the View).

Model data is passed to the request domain in these four ways.

Note: It is important to understand that SpringMVC actually converts all model data into ModelAndView eventually, whether you are a Map, a Model, etc., or if you have not returned a model data value and returned a "success" (equivalent to a view) SpringMVC also converts it into a ModelAndView object, which will be explained in detail in conjunction with the view and view parser.


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;

public class TestViewAndModel {
	public ModelAndView testModelAndView() {
		ModelAndView mv = new ModelAndView();
		String[] names = { "zz", "xx", "cc" };
		mv.addObject("names", names);
		return mv;
	public String testMap(Map<String, Object> map) {
		map.put("name", "maptest");
		return "success";
	public String testModel(Model model) {
		model.addAttribute("address", "changsha");
		return "success";
	public String testModelMap(ModelMap modelMap) {
		modelMap.addAttribute("modelMap", "modelMap");
		return "success";


3, inIndex.jspAdd the following code to the page.


	<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>


4, add the following code to the success in the views file.


	<h1>Success Page</h1><br>
	names: ${requestScope.names }<br>
	name : ${requestScope.name }<br>
	address: ${requestScope.address }<br>
	address: ${requestScope.modelMap }<br>

5. Run the process.


After writing the code, we access theIndex.jspThe address of the page, then annotated by RequestMapping, and finally go toSuccess.jspThe page gets the data we get behind the scenes.








Topics: Java