7.1 处理前端请求数据
原来httpservlet获取前端请求数据的方式
request.getParamete(“username”)
springmvc 处理提交数据
1、提交的域中参数名城和处理的参数名称一致
提交数据为http://localhost:8080/test11_war_exploded/test1111?name=baifu
处理方法:
@RequestMapping("/test1")
public String test(String username){
System.out.println(username);
return "test";
}
在页面输入在后台显示"baifu"
2、提交的域名城和树立的参数名称不一致, 使用@RequestParam,建议前端的参数都是用@RequestParam,方便区分
提交数据为http://localhost:8080/test11_war_exploded/test2222?username=baifu,这时候再用name=baifu就会报错了(400),只能用username了,@RequestParam(“username”)类似与别名
//@RequestParam("username") username是提交的域的名称。
@RequestMapping("/test1")
public String test(@RequestParam("username") String name){
System.out.println(name);
return "test";
}
3、前端提交的是一个对象
要求提交的表单和对象的属性名一致,方法参数使用对象即可
1、实体类
public class User {
private int id;
private int age;
private String name;
}
2、提交数据为 http://localhost:8080/test11_war_exploded/user?name=baifu&id=1&age=20
3、处理方法
@RequestMapping("/user")
public String user(User user, Model model){
System.out.println(user);
//将返回结果传递给前端
model.setAttribute("msg",name);
return "test";
}
}
后台输出 User(id=1,name=‘kuangshen’,age=15)_
1.接手前端用户传递的参数,判断参数名字,假设名字直接在方法上,则可以直接使用
- 假设传递的是一个对象user,匹配User对象中的字段名,如果名字一致则ok,否则匹配不到
http://localhost:8080/mvc03/user?username=kuangshen&id=1&age=20 如这个请求就无法匹配到,因为username和name不匹配
说明:如果使用对象的话,前端传递的参数和对象名必须一致,否则就是null;
7.2 数据显示到前端
1、通过ModelAndView
我们前面一直都是如此,就不用过多解释
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg", "ControllerTest1");
modelAndView.setViewName("test");
return modelAndView;
}
}
2.、通过Model
@RequestMapping(path ="/add/{a}/{b}",method= RequestMethod.GET )
public String test1(@PathVariable int a, @PathVariable int b, Model model){
int res = a+b;
model.addAttribute("msg","结果为"+res);
return "test";
}
3、通过ModelMap
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap modelMap){
//封装要显示到视图中的数据
//相当于req.setAttribute("name",name);
System.out.println(name);
return "hello";
}
对于新手而言,简单的来说使用区别就是
-
Model 知识寥寥几个方法适用于储存数据,简化了新手对于Model对象的操作和理解
-
ModelMap 继承了LinkedMap, 除了实现了自身的一些方法,同样的继承LinkedMap的方法和特性
-
ModelAndView 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的的挑战
当然更多的以后开发考虑的跟那更多的是性能和优化,就不能单单仅限于此的了解
请使用80%的时间打好扎实的基础,剩下18%的时间研究框架,2%的时间去学点英文,框架的官方文档永远是最好的教程
LinkedHashMap
ModelMap 继承LinkedHashMap,
Model 精简版