数据处理
1.提交的域名称和处理方法的参数名一致
http://localhost:8080/hello?name=yl
@RequestMapping("/hello")
public String hello(String name){
System.out.println(name);
return "hello";
}
2.提交的域名称和处理方法的参数名不一致
http://localhost:8080/hello?username=yl
//@RequestParam("username")
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "hello";
}
3.提交一个对象
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
//需要导入lombok
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
http://localhost:8080/springmvc/user?name=yl&age=11&sex=“男”
@RequestMapping("/user")
public String user(User user){
System.out.println(user);
return "hello";
}
若使用对象,前端传递的参数名和对象名必须一致,否则为null
数据显示至前端
-
ModelAndView
public class ControllerTest implements Controller { public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { //返回一个模型视图对象 ModelAndView mv = new ModelAndView(); mv.addObject("msg","C1"); 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 只有几个方法,只适用于储存数据
- ModelMap 继承了 LinkedMap ,除了实现了自身的一些方法,又继承 LinkedMap 的方法和特性
- ModelAndView 可以在储存数据时,设置返回的逻辑视图,实现控制展示层的跳转