SpringMVC的各种参数绑定方式
1. 基本数据类型(以int为例,其他类似):
Controller代码:
@RequestMapping("saysth.do")
public void test(int count) {
}
表单代码:
<form action="saysth.do" method="post"><input name="count" value="10" type="text"/>......</form>
表单中input的name值和Controller的参数变量名保持一致,就能完成数据绑定,如果不一致可以使用@RequestParam注解。需要注意的是,如果Controller方法参数中定义的是基本数据类型,但是从页面提交过来的数据为null或者”"的话,会出现数据转换的异常。也就是必须保证表单传递过来的数据不能为null或”",所以,在开发过程中,对可能为空的数据,最好将参数数据类型定义成包装类型,具体参见下面的例子。
2. 包装类型(以Integer为例,其他类似):
Controller代码:
@RequestMapping("saysth.do")publicvoid test(Integer count) {
}
表单代码:
<form action="saysth.do" method="post"><input name="count" value="10" type="text"/>......</form>
和基本数据类型基本一样,不同之处在于,表单传递过来的数据可以为null或”",以上面代码为例,如果表单中num为”"或者表单中无num这个input,那么,Controller方法参数中的num值则为null。
3. 自定义对象类型:
Model代码:
publicclass User {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
publicvoid setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
publicvoid setLastName(String lastName) {
this.lastName = lastName;
}
}

Controller代码:
@RequestMapping("saysth.do")publicvoid test(User user) {
}
表单代码:
<form action="saysth.do" method="post"><input name="firstName" value="张" type="text"/><input name="lastName" value="三" type="text"/>......</form>
非常简单,只需将对象的属性名和input的name值一一匹配即可。
4. 自定义复合对象类型:
Model代码:

publicclass ContactInfo {
private String tel;
private String address;
public String getTel() {
return tel;
}
publicvoid setTel(String tel) {
this.tel = tel;
}
public String getAddress() {
return address;
}
publicvoid setAddress(String address) {
this.address = address;
}
}publicclass User {
private String firstName;
private String lastName;
private ContactInfo contactInfo;
public String getFirstName() {
return firstName;
}
publicvoid setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
publicvoid setLastName(String lastName) {
this.lastName = lastName;
}
public ContactInfo getContactInfo() {
return contactInfo;
}
publicvoid setContactInfo(ContactInfo contactInfo) {
this.contactInfo = contactInfo;
}
}

Controller代码:

@RequestMapping("saysth.do")publicvoid test(User user) {
System.out.println(user.getFirstName());
System.out.println(user.getLastName());
System.out.println(user.getContactInfo().getTel());
System.out.println(user.getContactInfo().getAddress());
}

表单代码:

<form action="saysth.do" method="post"><input name="firstName" value="张"/><br><input name="lastName" value="三"/><br><input name="contactInfo.tel" value="13809908909"/><br><input name="contactInfo.address" value="北京海淀"/><br><input type="submit" value="Save"/></form>

User对象中有ContactInfo属性,Controller中的代码和第3点说的一致,但是,在表单代码中,需要使用“属性名(对象类型的属性).属性名”来命名input的name。
网友评论