SpringMvc框架实现前端向后端传数据
(1)直接将表单的name参数写在Controller类的方法参数中(注意要同名才能映射成功)
name:
password:
//后台controller,addUser方法的userName,password参数名称与表单的name同名才能映射得到数据
@RequestMapping(value = “/login”, method = RequestMethod.POST)
public String add(Model model, String name, String password){
…
}
(2)表单数据后台通过request来获取数据。同样使用上面的表单
@RequestMapping(value = “/login”,method=RequestMethod.POST)
public String addUser(HttpServletRequest request){
String userName = request.getParameter(“userName”);
String password = request.getParameter(“password”);
//… return “userlist”;
}
(3)表单数据封装前端数据到bean中
//定义一个user的类
public class User{
private String userName;
private String password;
//getter
public void setUserName(String userName){
this.userName = userName;
}
public void setPassword(String password){
this.password = password;
}
}
//controller中,就可以通过User user对象封装form表单数据
@RequestMapping(value = “/login”,method=RequestMethod.POST)
public String addUser(User user){
String userName = user.getUserName();
String password = user.getPassword();
//… return “userlist”;
}
(4)查询参数方式,通过HTTP发起的一个带有参数的RPC请求,请求的形式为“/aa?name=haha”
@RequestMapping(value = “/aa”, method = RequestMethod.POST)
public String func(Model model, @RequestParam(“name”) String name) {
…
}
(5)路径变量,直接请求资源,请求的形式为“/aa/haha”
@RequestMapping(value = “/aa/{name}”, method = RequestMethod.POST)
public String func(Model model, @PathVariable(“name”) String name) {
…
}
SpringMvc框架实现后端向前端传数据
(1)通过request对象
页面名称userAdd
添加用户信息
${personId }
@RequestMapping(“/add”)
public String add(HttpServletRequest request){
request.setAttribute(“personId”,12);
return “userAdd”;
}
(2)通过ModelAndView对象
@RequestMapping(“/add”)
public ModelAndView add(){
ModelAndView mav = new ModelAndView(“userAdd”);
mav.addObject(“personId”, 12);
return mav;
}
(3) 通过Model方式
@RequestMapping(value = “/add”, method = RequestMethod.POST)
public String add(Model model){
String personId = “12”
model.addAttribute(“personId”,personId);
return “userAdd”;
}
//或
@RequestMapping(value = “/add”, method = RequestMethod.POST)
public String add(Model model){
String personId = “12”
return personId;
}
(4)通过Map对象
@RequestMapping(value = “/add”, method = RequestMethod.POST)
public String add(Map map){
String personId = “12”
map.put(“personId”,personId);
return “userAdd”;
}