Spring MVC 提供了以下几种途径输出模型数据:
- ModelAndView:处理方法返回值类型为 ModelAndView时, 方法体即可通过该对象添加模型数据
- Map及Model:入参为org.springframework.ui.Model、org.springframework.ui.ModelMap或 java.uti.Map时,处理方法返回时,Map 中的数据会自动添加到模型中。
- @SessionAttributes: 将模型中的某个属性暂存到 HttpSession 中,以便多个请求之间可以共享这个属性
- @ModelAttribute: 方法入参标注该注解后, 入参的对象就会放到数据模型中
ModelAndView
概述
控制器处理方法的返回值如果为 ModelAndView, 则其既包含视图信息,也包含模型数据信息。
添加模型数据:
- MoelAndView addObject(String attributeName, Object attributeValue)
- ModelAndView addAllObject(Map< String, ?> modelMap )
设置视图:
- void setView(View view )
- void setViewName(String viewName)
示例
register_form.jsp
<!DOCTYPE HTML>
<html>
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<form action="model/register" method="post">
username: <input type="text" name="username"/>
<br>
password: <input type="password" name="password"/>
<br>
email: <input