SpringMVC學習(四)之使用POJO作為參數


當表單有眾多項時,像之前一個一個傳遞參數比較麻煩,可以使用POJO直接將表單數據存儲到實體類中


步驟一:創建POJO


package entity;

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

package entity;

public class User {
private String name;
private int age;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 [name=" + name + ", age=" + age + ", address=" + address
+ "]";
}

}

步驟二: 創建控制器


/**
*Spring MVC 會按請求參數名和 POJO 屬性名進行自動匹配,
*自動為該對象填充屬性值。支持級聯屬性
*/
@RequestMapping(value="/testPojo")
private String testPojo(User user) {
System.out.println("testPojo "+user);
return SUCCESS;
}

步驟三:請求表單


<form action="springmvc/testPojo" method="post">
用戶名:<input type="text" name="name"><br>
年齡:<input type="text" name="age"><br>
省份:<input type="text" name="address.province"><br>
城市:<input type="text" name="address.city"><br>
<input type="submit" value="submit">
</form>

0 個評論

要回覆文章請先登錄註冊