sring mvc 返回值至jsp界面的几种方式
Spring 通过Controller 向 View 传值的方法有以下四种
- HttpServletRequest
- ModelAndView
- Map<String, Object> map
- Model model
第一种
需要参数HttpServletRequest 返回值是jsp页面
@RequestMapping("/query1.do")
public String queryUser1(HttpServletRequest request){
String name = "张三";
request.setAttribute("name", name);
UserInfo user = new UserInfo();
user.setUserId(9257);
user.setUserName("华安");
request.setAttribute("user", user);
return "query";
}
第二种 ModelAndView 返回值是ModelAndView 参数不需要
@RequestMapping("/query2.do")
public ModelAndView queryUser2(){
UserInfo user = new UserInfo();
user.setUserId(1001);
user.setUserName("秋香");
//model
Map<String,Object> map = new HashMap<String,Object>();
map.put("user2", user);
return new ModelAndView("query",map);
}
第三种 参数是Map 返回值是jsp页面
@RequestMapping("/query3.do")
public String queryUser3(Map<String,Object> map){
UserInfo user = new UserInfo();
user.setUserId(1002);
user.setUserName("石榴");
map.put("user3", user);
return "query";
}
第四种 参数是Model 返回值是jsp 使用model的addAttribute方法
@RequestMapping("/query4.do")
public String queryUser4(Model model){
UserInfo user = new UserInfo();
user.setUserId(1);
user.setUserName("华夫人");
model.addAttribute("user4", user);
return "query";
}
但是无论哪一种方式 简单参数或对象都可以通过变量名来显示
userId:${user4.userId }
userName:${user4.userName }
但是数组的返回值会显示则会有问题,如:直接返回数组
@RequestMapping("/query5.do")
public String queryUser5(Model model){
UserInfo user = new UserInfo();
user.setUserId(1);
user.setUserName("华夫人");
List<UserInfo> list = new ArrayList<UserInfo>();
list.add(user);
list.add(user);
list.add(user);
model.addAttribute("list", list);
return "query";
}
userId:${list}
list:[UserInfo [userId=1, userPw=null, userName=华夫人, userAge=null, userBrithday=null, xqs=null], UserInfo [userId=1, userPw=null, userName=华夫人, userAge=null, userBrithday=null, xqs=null], UserInfo [userId=1, userPw=null, userName=华夫人, userAge=null, userBrithday=null, xqs=null]]