您的位置:首页 > 其它

4、使用POJO对象绑定请求参数值

2017-11-12 17:50 363 查看
当发送过来一个JSP请求时,spring mvc会按请求中的参数名和POJO对象属性中的名进行自动匹配,通过POJO中的set方法进行映射,自动为POJO对象的属性填充值。在创建POJO类时,可以创建一个无参构造器,但是不需要创建一个有参构造器,因为给POJO对象的属性赋值是通过映射,而不再是有参构造器,一旦有有参构造器的话,反而会出错,spring不知道如何去初始化。POJO中支持级联属性。下面通过例子演示:

首先进行web.xml和spring的xml配置,配置方法同SpringMVC之注解RequestMapping用法一节中一样。

一、创建POJO类

创建一个user类

public class User {

private String username;
private String password;
private int age;
private Address address;

public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", age=" + age + ", address=" + address + "]";
}
}


user类中一个address属性又是一个POJO对象,因此创建user的一个级联类Address

public class Address {

private String city;
private String province;

public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
@Override
public String toString() {
return "Address [city=" + city + ", province=" + province + "]";
}
}


二、创建请求JSP

index.jsp为测试发送请求,index.jsp中的内容为:

<form action="springMVC/testPojo" method="post">
username: <input type="text" name="username"/>
<br>
password: <input type="password" name="password"/>
<br>
age: <input type="text" name="age"/>
<br>
city: <input type="text" name="address.city"/>
<br>
province: <input type="text" name="address.province"/>
<br>
<input type="submit" value="Submit"/>
</form>


三、处理请求的控制器

下面为处理index.jsp中action请求的控制器方法

@Controller
@RequestMapping("/springMVC")
public class TestSpringMVC {

@RequestMapping("/testPojo")
public String testPojo(User user){
System.out.println("testPojo: " + user);
return "success";
}
}


index.jsp中的form表单中username、password、age、address.city、address.province填入要发送的内容,点击submit发送请求,控制器截获请求后,会把表单中对应的属性和user对象中的属性进行匹配,并把表单中的值自动填入user对象属性中。执行后,控制台输出:

testPojo: User [username=lzj, password=12345, age=20, address=Address [city=jining, province=shandong]]


注意:如果自创建POJO类时,创建了带属性的构造器,会报如下错误:
Could not instantiate bean class [com.lzj.springmvc.handlers.User]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.lzj.springmvc.handlers.User.<init>()
表示spring 在初始化user对象时,没有默认的无参构造器,导致不能初始化POJO对象,可见spring是通过无参构造器进行初始化bean的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: