1、控制器处理方法的返回值如果为 ModelAndView, 则其既包含视图信息,也包含模型数据信息。
(1)添加模型数据
MoelAndView addObject(String attributeName, Object attributeValue);
(2)设置视图:
public void setViewName(String viewName);
(3)同时设置视图和模型数据
HashMap model = new HashMap();
model.put("beginDt", beginDt);
new ModelAndView(viewName, model);
2、案例一:分时设置视图和模型数据
(1)控制器TestRequestMappingController.java
package com.springmvc.web.controller;
import java.util.HashMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/springmvc")
public class TestRequestMappingController {
@RequestMapping("/testModelAndView1")
public ModelAndView testModelAndView1() {
ModelAndView modelAndView = new ModelAndView("success");
modelAndView.addObject("username", "lipiaoshui");
return modelAndView;
}
}
(2)访问代码
<a href="<%=path%>/springmvc/testModelAndView1">Test ModelAndView1</a>
3、案例二:通过构造函数同时设置视图和模型数据
(1)控制器TestRequestMappingController.java
package com.springmvc.web.controller;
import java.util.HashMap;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/springmvc")
public class TestRequestMappingController {
@RequestMapping("/testModelAndView2")
public ModelAndView testModelAndView2() {
HashMap<String, Object> model = new HashMap<String, Object>();
model.put("username", "zhangsan");
return new ModelAndView("success", model);
}
}
(2)访问代码
<a href="<%=path%>/springmvc/testModelAndView2">Test ModelAndView2</a>