spring mvc封装数据的对象有HttpSession、HttpServletRequest、HttpServletResponse、ModelAndView、ModelMap、Model、Map
Map map,Model model,ModelMap modelmap,ModelAndView mav,HttpServletRequest request 声明变量
request.getSession().setAttribute("test", "hello spring mvc!");
request.setAttribute("test", "hello spring mvc!");
mav.addObject("test","hello spring mvc!");
modelmap.addAttribute("test", "hello spring mvc!");
model.addAttribute("test", "hello spring mvc!");
map.put("test","hello spring mvc!");
在跳转页面可以通过${test}方式取值,优先取Map、Model和ModelMap的,Map、Model和ModelMap是同一个东西,谁最后赋值的就取谁的,然后是request,最后是从session中获取
假如想直接取request.getParameter("test"),则用${param.test}
@Controller
//0.使用Session在回话中传递参数
@SessionAttributes(value="message")
public class IndexController{
//1.使用request获取页面数据,并传递给跳转页面
@RequestMapping(value="index1")
public String hello1(HttpServletRequest request) {
String s1=request.getParameter("userName");
System.out.println(s1);
request.setAttribute("message", s1);
return "hello";
}
//2.使用ModelAndVies包装返回页面数据
@RequestMapping(value="index2")
public ModelAndView hello2(String userName) {
System.out.println(userName);
ModelAndView mav=new ModelAndView("hello");
mav.addObject("message", userName);
return mav;
}
//3.使用ModelMap包装返回页面数据
@RequestMapping(value="index3")
//@RequestParam("userName")String name 接收的参数为userName,为其起名为name
public String hello3(@RequestParam("userName")String name,ModelMap mm) {
System.out.println(name);
String s3=name;
mm.addAttribute("message", s3);
return "hello";
}
//4.使用Model包装返回页面数据
@RequestMapping(value="index4")
//@RequestParam("userName")String name 接收的参数为userName,为其起名为name
public String hello4(@RequestParam("userName")String name,Model model) {
System.out.println(name);
String s3=name;
model.addAttribute("message", s3);
return "hello";
}
//5.使用Map包装返回页面数据
@RequestMapping(value="index5")
public String hello5(String userName,Map map) {
System.out.println(userName);
String s4=userName;
map.put("message", s4);
return "hello";
}
//6.使用Map包装对象
@RequestMapping(value="index6")
public String hello6(userInfo userinfo,Map map) {
System.out.println(userinfo);
Date date=new Date();
userinfo.setDate(date);
map.put("message", userinfo);
return "hello";
}
//7. 测试返回页面取值对Map、Model、ModelMap、ruquest、session的设值的先后
@RequestMapping(value="index7")
public String hello7(HttpServletRequest request,HttpServletResponse response,Map map,Model model,ModelMap mm) {
String s1=request.getParameter("userName");
mm.addAttribute("message", "天明mm");
model.addAttribute("message", "天明model");
map.put("message","天明map");
request.setAttribute("message", s1);
return "hello";
}
}