Spring MVC返回數據到頁面有幾種不一樣的方式,它們各自適用的狀況也不一樣,下面簡單總結一下。html
對於每種方式都給出Controller中的相應方法。java
首先仍是頁面user_add.jsp。它既是發出請求的頁面,也是接收返回結果的頁面:spring
<%@ page language="java" import="java.util.*" contentType="text/html;charset=utf-8"%> <html> <head> <title></title> </head> <body> <h1>添加用戶信息4</h1> <form action="user/add4.do" method="post"> <input type="submit" value="提交"> </form> ${personId } </body> </html>
一、經過request對象:app
@RequestMapping("/add.do")
public String add(HttpServletRequest request){
request.setAttribute("personId",12);
return "user_add";
}jsp
二、經過ModelAndView對象:post
@RequestMapping("/add.do")
public ModelAndView add(){
ModelAndView mav = new ModelAndView("user_add");
mav.addObject("personId", 12);
return mav;
}spa
三、經過Model對象:code
@RequestMapping("/add.do")
public String add(Model model){
model.addAttribute("personId", 12);
return "user_add";
}orm
四、經過Map對象:htm
@RequestMapping("/add.do") public String add(Map<String,Object> map){ map.put("personId", 12); return "user_add"; }