springmvc参数绑定过程
- 从客户端请求key/value数据,经过参数绑定,将key/value数据绑定到controller方法的形参上。
- springmvc中,接收页面提交的数据是通过方法形参来接收,而不是在controller类定义成员变量接收。
基本数据类型绑定
页面准备form表单如下:
<form action="<%=request.getContextPath()%>/login_no_send_400.do" method="post">
id:<input type="text" name="id"/><br>
username:<input type="text" name="username"/><br>
password:<input type="text" name="password"/><br>
sex:<input type="text" name="sex"/><br>
学费:<input type="text" name="price"/><br>
状态:<input type="text" name="state"/><br>
<input type="submit" name="Login"/><br>
</form>
在Controller中获取表单数据方式如下:
使用这种方式获取表单数据时,若是在表单提交如果没有给值,那么会报400错误!这样使得提交表单必须有值,否则出错;
@RequestMapping("login.do")
public ModelAndView login(int id,String username,String password,char sex,double price,boolean state)
{
//我们这个方法怎么能够获取表单数据呢?
//String idstr=request.getParameter("id");
//int id=Integer.parseInt(idstr);
System.out.println(id);
System.out.println(username);
System.out.println(password);
System.out.println(sex);
System.out.println(price);
System.out.println(state);
return null;
}
既然以上的方式获取表单数据时,表单没有数据就会出现400的错误,那么使用基本数据类型的封装类型就不会出现此类问题。
//这个方法的参数绑定都是封装类型,那么允许数据为null,所以表单有数据为空,后台接收不会报400错误
@RequestMapping("login_no_send_400.do")
public ModelAndView login_no_send_400(Integer id,String username,String password,Character sex,Double price,Boolean state)
{
System.out.println(id);
System.out.println(username);
System.out.println(password);
System.out.println(sex);
System.out.println(price);
System.out.println(state);
return null;
}
封装类型绑定(POJO绑定)
使用以上方式的获取表单数据显然有些不和理,将数据封装到对象里面才是Java应该,通过对象拿数据,这才是正确的做法。
那上面的表单来说,有id、username、password、sex、price、state这些属性,定义一个实体类。将这些属性加到实体中,在请求时Spring自动为我将表单的数据封装到对象中去。前提就是form表单的name属性要和类的属性一致。
定义实体类如下:
public class User {
private Integer id;
private String username;
private String password;
private Character sex;
private Double price;
private Boolean state;
//get和set方法这里省略不写
}
通过对数据的封装,获取表单数据就简单得多。
至于spring是如何实现这个功能的,那就需要debug看源码就可以知道一二了。
/*
* 这个方法限定请求方式必须是post
*/
@RequestMapping("register.do")
public ModelAndView register(User user) //轻松地拿到了form表单的数据
{
return null;
}