Version: Next
ModelAndView
处理提交数据
提交的域名称和处理方法的参数名不一致
http://localhost:8080/hello?username=bsx
@Controllerpublic class RESTFulController {@RequestMapping("/hello")public String hello(@RequestParam("username") String name){System.out.println(name);return "hello";}}推荐任何时候都把@RequestParam加上
提交的是一个对象 http://localhost:8080/hello/user?name=bsx&id=1&age=18
public class User {private int id;private String name;private int age;}@Controllerpublic class RESTFulController {@RequestMapping("/user")public String hello(User user){System.out.println(user);return "hello";}}参数名和属性名对应不上的话就不匹配不上,无法对应的值会被设定为null
数据显示到前端
ModelAndView
@RequestMapping("/tset1")
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
ModelMap
继承了LinkedHashMap
@RequestMapping("/test2")
public String hello(@RequestParam("username") String name, ModelMap model){
//封装要显示到视图中的数据
//相当于req.setAttribute("name",name);
model.addAttribute("name",name);
System.out.println(name);
return "hello";
}
Model
精简版ModelMap,大部分情况下用Model就够了
@RequestMapping("/test3")
public String hello(@RequestParam("username") String name, Model model){
//封装要显示到视图中的数据
//相当于req.setAttribute("name",name);
model.addAttribute("msg",name);
System.out.println(name);
return "test";
}
Model
:几个简单的方法用于存储数据,简化了新手对Model对象的操作和理解ModelMap
:继承了LinkedHashMap
,具有LinkedHashMap
的方法和特性ModelAndView
:可以在存储数据的同时,可以设置返回的逻辑视图。