Spring MVC 会按请求参数名和 POJO 属性名进行自动匹配 , 自动为该对象填充属性值 , 支持级联属性。如:address.province。
package com.itdoc.springmvc.entities; /**
* @BLOG http://www.cnblogs.com/goodcheap
* @DESCRIBE
* @AUTHOR WángChéngDá
* @DATE 2017-03-09 11:35
*/
public class User { private String username; private int age; private String password; private String email; private Address address; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public Address getAddress() {
return address;
} public void setAddress(Address address) {
this.address = address;
} @Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", age=" + age +
", password='" + password + '\'' +
", email='" + email + '\'' +
", address=" + address +
'}';
}
}
package com.itdoc.springmvc.entities; /**
* @BLOG http://www.cnblogs.com/goodcheap
* @DESCRIBE
* @AUTHOR WángChéngDá
* @DATE 2017-03-09 11:37
*/
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 com.itdoc.springmvc.entities; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; /**
* @BLOG http://www.cnblogs.com/goodcheap
* @DESCRIBE
* @AUTHOR WángChéngDá
* @DATE 2017-03-09 11:38
*/
@Controller
public class TestPojo { public static final String SUCCESS = "success"; @RequestMapping(value = "/getPojo", method = RequestMethod.POST)
public String getPojo(User user) {
System.out.println(user);
return SUCCESS;
}
}
<%--
User: WángChéngDá
Date: 2017-03-08
Time: 11:40
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<form action="/getPojo" method="post">
username:<input type="text" name="username"/>
<br>
password:<input type="password" name="password"/>
<br>
age:<input type="text" name="age"/>
<br>
email:<input type="text" name="email"/>
<br>
province:<input type="text" name="address.province"/>
<br>
city:<input type="text" name="address.city"/>
<br>
<input type="submit" value="submit"/>
</form>
</body>
</html>