Spring MVC 會按請求參數名和 POJO 屬性名進行自動匹配,自動爲該對象填充屬性值。支持級聯屬性。如:dept.deptId、dept.address等html
說的通俗點就是,平時咱們想將請求頁面的表單數據接收並封裝成特定對象的時候,少不了作的是在某個servlet的對應方法中從request中將各個表單參數取出,類型轉換好,構造一個特定類型的對象,再把表單參數都存進去。java
只要你能保證請求頁面的表單輸入項的name與POJO對象類的域名稱相同便可。spring
另外,springMVC的該功能還支持級聯屬性,也就是支持POJO中的域是另外一個POJO對象的狀況。相應地,表單的name寫爲:pojo1的域名.pojo2的域名app
例如:jsp
Person類ide
public class Person { 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 Location getLocal() { return local; } public void setLocal(Location local) { this.local = local; } String username; int age; Location local; @Override public String toString() { return "Person [username=" + username + ", age=" + age + ", local=" + local + "]"; } }
Location類post
public class Location { 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; } String city; String province; @Override public String toString() { return "Location [city=" + city + ", province=" + province + "]"; } }
Controller
this
@Controller @RequestMapping("/roger") public class PojoRequestController { @RequestMapping(value = "/addPerson") public String addPerson() { return "addPerson"; } @@RequestMapping(value = "/showPerson", method = RequestMethod.POST) public String showPerson(PrintWriter printWriter, Person person) { System.out.println("person:" + person.getName() + " " + person.getLocal().getCity()); printWriter.println("name:" + person.getName()); printWriter.println("city" + person.getLocal().getCity()); return null; } }
addPerson.jspcode
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title></title> </head> <body> <form action="showPerson" method="post"> name:<input type="text" name="name"/> <br> city:<input type="text" name="local.city"/> <br> <input type="submit" value="add"/> </form> </body>
注意:orm
若是請求的表單參數中不存在pojo對象中的某個域名稱的項目,則綁定後pojo該屬性爲null。
若是請求的表單參數中存在pojo對象中沒有包含的域的項目,則綁定後該參數丟失。
若是表單項目的數據會自動從String轉換爲相應pojo的域類型。但若是類型沒法轉換,則報錯。若是我輸入age爲dafsdfa,那麼報錯。