标签:
Command or form objects to bind request parameters to bean properties (via setters) or directly to fields, with customizable type conversion, depending on @InitBinder methods and/or the HandlerAdapter configuration. See the webBindingInitializer property on RequestMappingHandlerAdapter. Such command objects along with their validation results will be exposed as model attributes by default, using the command class class name - e.g. model attribute "orderAddress" for a command object of type "some.package.OrderAddress". The ModelAttribute annotation can be used on a method argument to customize the model attribute name used.
可以使用POJO类作为@RequestMapping方法的参数,SpringMVC会自动的将值,注入到POJO属性名与URL上参数名一致的属性中。并支持联级属性。
代码:
1: public class User {2: private String name;3: private Integer age;4: private Address address;5:
6: public String getName() {7: return name;8: }
9:
10: public void setName(String name) {11: this.name = name;12: }
13:
14: public Integer getAge() {15: return age;16: }
17:
18: public void setAge(Integer age) {19: this.age = age;20: }
21:
22: public Address getAddress() {23: return address;24: }
25:
26: public void setAddress(Address address) {27: this.address = address;28: }
29:
30: @Override
31: public String toString() {32: return "User{" +33: "name=‘" + name + ‘\‘‘ +34: ", age=" + age +35: ", address=" + address +36: ‘}‘;37: }
38: }
39:
40: public class Address {41: private String province;42: private String city;43:
44: public String getProvince() {45: return province;46: }
47:
48: public void setProvince(String province) {49: this.province = province;50: }
51:
52: public String getCity() {53: return city;54: }
55:
56: public void setCity(String city) {57: this.city = city;58: }
59:
60: @Override
61: public String toString() {62: return "Address{" +63: "province=‘" + province + ‘\‘‘ +64: ", city=‘" + city + ‘\‘‘ +65: ‘}‘;66: }
67: }
68:
69: @Controller
70: public class TestPOJO {71:
72: @RequestMapping("/testPOJO")73: public String testPOJO(User user) {74: System.out.println(user);
75: return "success";76: }
77: }
URL:
1: <form action="testPOJO">2: <label>name:</label> <input type="text" name="name"/>3: <br/>4: <label>age:</label> <input type="text" name="age"/>5: <br/>6: <label>province:</label> <input type="text" name="address.province"/>7: <br/>8: <label>city:</label> <input type="text" name="address.city"/>9: <br/>10: <input type="submit" value="testPOJO"/>11: </form>
SpringMVC(六)POJO类作为 @RequestMapping方法的参数
标签:
原文地址:http://www.cnblogs.com/FFFFF/p/4627157.html