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)
实例:
Student类存储数据
package com.qst.Obj;
import org.springframework.stereotype.Component;
@Component
public class Student {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
}
index入口页面
<a href="testmodel">Test model</a>
<br>
ModelAndView
package com.qst.hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.qst.Obj.Student;
@Controller
public class modelandview {
@Autowired
private Student student;
@RequestMapping("/testmodel")
public ModelAndView model() {
String viewname = "success";
ModelAndView mod = new ModelAndView(viewname);
student.setId(1);
student.setName("zs");
//添加数据到模型
mod.addObject("stu", student);
return mod;
}
}
success.jsp显示Student的所有信息
<h4>Success Page</h4>
${stu}
结语:
以梦为马,不负韶华
流年笑掷,未来可期