6.1、处理提交数据
6.1.1、提交的域名称和处理方法的参数名一致
提交: http://localhost:8080/hello?name=ssys
处理方法:
@RequestMapping("/hello")
public String hello(String name){
System.out.println(name);
retrun "hello";
}
后台输出: ssys
6.1.2、提交的域名称和处理方法的参数名不一致
提交: http://localhost:8080/hello?username=ssys
处理方法: @RequstParam(“username”) // username是前端提交的域的名称
建议无论域名称和处理方法的参数名是否一致只要是从前端获取的参数, 全部用这个注解
@RequestMapping("/hello")
public String hello(@RequstParam("username") String name){
System.out.println(name);
retrun "hello";
}
6.1.3、提交一个对象
要求提交的表单域和对象的属性名一致,参数使用对象即可
实体类
@Data
public class User{
private int id;
private String name;
private int age;
}
提交数据: http://localhost:8080/hello?name=ssys&id=1&age=18
处理方法:
@RequestMapping("/hello")
public String user(User user){
System.out.println(user);
retrun "test";
}
后台输出: User{id=1, name=‘ssys’, age=18}
注意: 如果使用对象传参, 前端传递的参数名与对象名必须一致,否则就是null
6.2、数据显示到前端
6.2.1、通过ModelAndView(一般xml配置方式用)
前面曾提到, 不在过多解释
public class Controller01 implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//返回一个模型视图
ModelAndView mv = new ModelAndView();
mv.addObject("msg","Controller01");
mv.setViewName("test");
return mv;
}
}
6.2.2、通过ModelMap
@Controller
@RequestMapping("/user")
public class UserController {
//http://localhost:8080/user/t1?name=**
@GetMapping("/t1")
public String test1(@RequestParam("username") String name, ModelMap model) {
//1.接受前端参数
System.out.println("接受到前端的参数为: " + name);
//2.将返回的结果传递给前端
model.addAttribute("msg", "\n" + name);
//3.跳转视图
return "test";
}
}
6.2.3、通过model(一般注解方式用)
前面曾提到, 不在过多解释
@Controller
@RequestMapping("/user")
public class UserController {
//http://localhost:8080/user/t1?name=**
@GetMapping("/t1")
public String test1(@RequestParam("username") String name, Model model) {
//1.接受前端参数
System.out.println("接受到前端的参数为: " + name);
//2.将返回的结果传递给前端
model.addAttribute("msg", "\n" + name);
//3.跳转视图
return "test";
}
}
小结(对比):
LinkedHashMap
Model : ModelMap的精简版(大部分情况, 我们都直接使用Model)
只有寥寥几个方法只适合存储数据, 简化了新手岁Model的操作和理解
ModelMap : 继承了LinkedHashMap, 所以他拥有LinkedHashMap的全部功能(方法和特性)
ModelAndView : 可以在存储数据的同时, 设置返回的逻辑视图, 进行控制展示层的跳转