前端数据处理方式
接收
// http://localhost:8080/user/t1?name=123
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/t1")
public String test1(String name, Model model){
// 1. 接收前端参数
System.out.println(name);
// 2. 将返回的结果传递给前端,Model
model.addAttribute("msg","链接传递的信息是:"+name);
// 3. 试图跳转
return "test";
}
}
// http://localhost:8080/user/t1?username=123
// @RequestParam表示是从前端接收的,固定名字。
@Controller
@RequestMapping("/user")
public class UserController {
@GetMapping("/t1")
public String test1(@RequestParam("username")String name, Model model){
// 1. 接收前端参数
System.out.println(name);
// 2. 将返回的结果传递给前端,Model
model.addAttribute("msg","链接传递的信息是:"+name);
// 3. 试图跳转
return "test";
}
// http://localhost:8080/user/t2?id=1&name=aaaa&age=3
@GetMapping("/t2")
public String test2(User user){
System.out.println(user);
return "test";
}
}
展示
- 通过ModelAndView
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一个模型视图对象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
- 通过ModelMap
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
//封装要显示到视图中的数据
//相当于req.setAttribute("name",name);
model.addAttribute("name",name);
System.out.println(name);
return "hello";
}
- 通过Model
@RequestMapping("/ct2/hello")
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 继承了 LinkedMap ,除了实现了自身的一些方法,同样的继承 LinkedMap 的方法和特性;
ModelAndView 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转。