Spring MVC 提供了如下几种途径输出模型数据:html
下面,咱们逐一来介绍这四种处理模型数据的方法:java
控制器处理方法的返回值若是为 ModelAndView, 则其既包含视图信息,也包含模型数据信息。spring
– MoelAndView addObject(String attributeName, Object attributeValue)
– ModelAndView addAllObject(Map<String, ?> modelMap)mvc
– void setView(View view)
– void setViewName(String viewName)app
<a href="springmvc/testModelAndView">test ModelAndView</a> <br><br>
/** * 目标方法的返回值能够是 ModelAndView 类型。 * 其中能够包含视图和模型信息 * SpringMVC 会把 ModelAndView 的 model 中数据放入到 request 域对象中. * @return */ @RequestMapping("/testModelAndView") public ModelAndView testModelAndView() { String viewName=SUCCESS; ModelAndView modelAndView=new ModelAndView(viewName); //添加模型数据到ModelAndView中 modelAndView.addObject("time", new Date()); return modelAndView; }
success.jsp中增长“${requestScope.time}”,以取得modelAndView中的数据:jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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>Insert title here</title> </head> <body> <h4>Success Page!</h4> time: ${requestScope.time} </body> </html>
最后运行结果:ui