SpringMVC Data Binding instance details, springmvc details

Source: Internet
Author: User
Tags null null

SpringMVC Data Binding instance details, springmvc details

SpringMVC Data Binding

Check the spring source code to see the data types that spring supports conversion:

Org. springframework. beans. PropertyEditorRegistrySupport:

/**  * Actually register the default editors for this registry instance.  */ private void createDefaultEditors() {   this.defaultEditors = new HashMap<Class, PropertyEditor>(64);    // Simple editors, without parameterization capabilities.   // The JDK does not contain a default editor for any of these target types.   this.defaultEditors.put(Charset.class, new CharsetEditor());   this.defaultEditors.put(Class.class, new ClassEditor());   this.defaultEditors.put(Class[].class, new ClassArrayEditor());   this.defaultEditors.put(Currency.class, new CurrencyEditor());   this.defaultEditors.put(File.class, new FileEditor());   this.defaultEditors.put(InputStream.class, new InputStreamEditor());   this.defaultEditors.put(InputSource.class, new InputSourceEditor());   this.defaultEditors.put(Locale.class, new LocaleEditor());   this.defaultEditors.put(Pattern.class, new PatternEditor());   this.defaultEditors.put(Properties.class, new PropertiesEditor());   this.defaultEditors.put(Resource[].class, new ResourceArrayPropertyEditor());   this.defaultEditors.put(TimeZone.class, new TimeZoneEditor());   this.defaultEditors.put(URI.class, new URIEditor());   this.defaultEditors.put(URL.class, new URLEditor());   this.defaultEditors.put(UUID.class, new UUIDEditor());    // Default instances of collection editors.   // Can be overridden by registering custom instances of those as custom editors.   this.defaultEditors.put(Collection.class, new CustomCollectionEditor(Collection.class));   this.defaultEditors.put(Set.class, new CustomCollectionEditor(Set.class));   this.defaultEditors.put(SortedSet.class, new CustomCollectionEditor(SortedSet.class));   this.defaultEditors.put(List.class, new CustomCollectionEditor(List.class));   this.defaultEditors.put(SortedMap.class, new CustomMapEditor(SortedMap.class));    // Default editors for primitive arrays.   this.defaultEditors.put(byte[].class, new ByteArrayPropertyEditor());   this.defaultEditors.put(char[].class, new CharArrayPropertyEditor());    // The JDK does not contain a default editor for char!   this.defaultEditors.put(char.class, new CharacterEditor(false));   this.defaultEditors.put(Character.class, new CharacterEditor(true));    // Spring's CustomBooleanEditor accepts more flag values than the JDK's default editor.   this.defaultEditors.put(boolean.class, new CustomBooleanEditor(false));   this.defaultEditors.put(Boolean.class, new CustomBooleanEditor(true));    // The JDK does not contain default editors for number wrapper types!   // Override JDK primitive number editors with our own CustomNumberEditor.   this.defaultEditors.put(byte.class, new CustomNumberEditor(Byte.class, false));   this.defaultEditors.put(Byte.class, new CustomNumberEditor(Byte.class, true));   this.defaultEditors.put(short.class, new CustomNumberEditor(Short.class, false));   this.defaultEditors.put(Short.class, new CustomNumberEditor(Short.class, true));   this.defaultEditors.put(int.class, new CustomNumberEditor(Integer.class, false));   this.defaultEditors.put(Integer.class, new CustomNumberEditor(Integer.class, true));   this.defaultEditors.put(long.class, new CustomNumberEditor(Long.class, false));   this.defaultEditors.put(Long.class, new CustomNumberEditor(Long.class, true));   this.defaultEditors.put(float.class, new CustomNumberEditor(Float.class, false));   this.defaultEditors.put(Float.class, new CustomNumberEditor(Float.class, true));   this.defaultEditors.put(double.class, new CustomNumberEditor(Double.class, false));   this.defaultEditors.put(Double.class, new CustomNumberEditor(Double.class, true));   this.defaultEditors.put(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, true));   this.defaultEditors.put(BigInteger.class, new CustomNumberEditor(BigInteger.class, true));    // Only register config value editors if explicitly requested.   if (this.configValueEditorsActive) {     StringArrayPropertyEditor sae = new StringArrayPropertyEditor();     this.defaultEditors.put(String[].class, sae);     this.defaultEditors.put(short[].class, sae);     this.defaultEditors.put(int[].class, sae);     this.defaultEditors.put(long[].class, sae);   } } 

The following describes some common data types and their binding methods.

1. Basic data type (taking int as an example, others are similar ):

Controller code:

@RequestMapping("test.do") public void test(int num) {    } 

JSP form code:

<form action="test.do" method="post">   <input name="num" value="10" type="text"/>   ...... </form> 

The name value of input in the form must be consistent with the name of the Controller parameter variable to complete data binding of the basic data type. If they are inconsistent, use the @ RequestParam annotation. It is worth mentioning that if the Controller method parameter defines the basic data type, but the data submitted from jsp is null or "", the data conversion exception will occur. That is to say, we must ensure that the data transmitted from the form cannot be null or "". Therefore, during development, it is best to define the parameter data type as the packaging type for data that may be null, for details, see the second article below.

2. packaging type (taking Integer as an example, others are similar ):

Controller code:

@RequestMapping("test.do") public void test(Integer num) {    } 

JSP form code:

<form action="test.do" method="post">   <input name="num" value="10" type="text"/>   ...... </form> 

Similar to the basic data type, the difference is that the data passed through the JSP form can be null or "". The above code is used as an example, if the input value of num in jsp is "" or does not exist in the form, the num value in the Controller method parameter is null.

3. Custom object type:

Model Code:

public class User {    private String firstName;    private String lastName;    public String getFirstName() {     return firstName;   }    public void setFirstName(String firstName) {     this.firstName = firstName;   }    public String getLastName() {     return lastName;   }    public void setLastName(String lastName) {     this.lastName = lastName;   }  } 

Controller code:

@RequestMapping("test.do") public void test(User user) {    } 

JSP form code:

<Form action = "test. do "method =" post "> <input name =" firstName "value =" Zhang "type =" text "/> <input name =" lastName "value =" 3 "type = "text"/> ...... </form>

It is very simple. You only need to match the property name of the object with the name value of input one by one.

4. Custom composite object types:

Model Code:

public class ContactInfo {    private String tel;    private String address;    public String getTel() {     return tel;   }    public void setTel(String tel) {     this.tel = tel;   }    public String getAddress() {     return address;   }    public void setAddress(String address) {     this.address = address;   }  }  public class User {    private String firstName;    private String lastName;    private ContactInfo contactInfo;    public String getFirstName() {     return firstName;   }    public void setFirstName(String firstName) {     this.firstName = firstName;   }    public String getLastName() {     return lastName;   }    public void setLastName(String lastName) {     this.lastName = lastName;   }    public ContactInfo getContactInfo() {     return contactInfo;   }    public void setContactInfo(ContactInfo contactInfo) {     this.contactInfo = contactInfo;   }  } 

Controller code:

@RequestMapping("test.do") public void test(User user) {   System.out.println(user.getFirstName());   System.out.println(user.getLastName());   System.out.println(user.getContactInfo().getTel());   System.out.println(user.getContactInfo().getAddress()); } 

JSP form code:

<Form action = "test. do "method =" post "> <input name =" firstName "value =" Zhang "/> <br> <input name =" lastName "value =" 3 "/> <br> <input name = "contactInfo. tel "value =" 13809908909 "/> <br> <input name =" contactInfo. address "value =" Beijing Haidian "/> <br> <input type =" submit "value =" Save "/> </form>

The User object has the ContactInfo attribute. The code in the Controller is the same as that in point 3rd. However, in the jsp code, you must use the "attribute name (attribute of the object type ). name of input.

5. List binding:

List needs to be bound to an object, but cannot be directly written in the parameters of the Controller method.

Model Code:

public class User {    private String firstName;    private String lastName;    public String getFirstName() {     return firstName;   }    public void setFirstName(String firstName) {     this.firstName = firstName;   }    public String getLastName() {     return lastName;   }    public void setLastName(String lastName) {     this.lastName = lastName;   }  }      public class UserListForm {    private List<User> users;    public List<User> getUsers() {     return users;   }    public void setUsers(List<User> users) {     this.users = users;   }  } 

Controller code:

@RequestMapping("test.do") public void test(UserListForm userForm) {   for (User user : userForm.getUsers()) {     System.out.println(user.getFirstName() + " - " + user.getLastName());   } } 

JSP form code:

<form action="test.do" method="post">   <table>    <thead>      <tr>       <th>First Name</th>       <th>Last Name</th>      </tr>    </thead>    <tfoot>      <tr>       <td colspan="2"><input type="submit" value="Save" /></td>      </tr>    </tfoot>    <tbody>      <tr>       <td><input name="users[0].firstName" value="aaa" /></td>       <td><input name="users[0].lastName" value="bbb" /></td>      </tr>      <tr>       <td><input name="users[1].firstName" value="ccc" /></td>       <td><input name="users[1].lastName" value="ddd" /></td>      </tr>      <tr>       <td><input name="users[2].firstName" value="eee" /></td>       <td><input name="users[2].lastName" value="fff" /></td>      </tr>    </tbody>   </table> </form> 

In fact, this is a bit similar to the contantInfo data binding in the User object at, but the attributes in the UserListForm object are defined as List instead of common custom objects. Therefore, you must specify the subscript of List in JSP. It is worth mentioning that Spring will create a List object with the maximum value as the size. Therefore, if the JSP form contains dynamic addition and deletion of rows, pay special attention to it, for example, after you delete rows and Add rows multiple times during use of a table, the value of the lower mark is inconsistent with the actual size. In this case, the objects in the List, the value is null only when the corresponding submark is in the jsp form. For example:

JSP form code:

<form action="test.do" method="post">   <table>    <thead>      <tr>       <th>First Name</th>       <th>Last Name</th>      </tr>    </thead>    <tfoot>      <tr>       <td colspan="2"><input type="submit" value="Save" /></td>      </tr>    </tfoot>    <tbody>      <tr>       <td><input name="users[0].firstName" value="aaa" /></td>       <td><input name="users[0].lastName" value="bbb" /></td>      </tr>      <tr>       <td><input name="users[1].firstName" value="ccc" /></td>       <td><input name="users[1].lastName" value="ddd" /></td>      </tr>      <tr>       <td><input name="users[20].firstName" value="eee" /></td>       <td><input name="users[20].lastName" value="fff" /></td>      </tr>    </tbody>   </table> </form> 

At this time, userForm In the Controller. getUsers () obtains the List size as 21, and the 21 User objects are not null. However, the firstName and lastName values of the User objects from 2nd to 19th are both null. Print result:

aaa - bbb ccc - ddd null - null null - null null - null null - null null - null null - null null - null null - null null - null null - null null - null null - null null - null null - null null - null null - null null - null null - null eee - fff 

6. Set binding:

Similar to List, Set needs to be bound to an object, but cannot be directly written in parameters of the Controller method. However, when binding Set data, you must add a corresponding number of model objects to the Set object.

Model Code:

public class User {    private String firstName;    private String lastName;    public String getFirstName() {     return firstName;   }    public void setFirstName(String firstName) {     this.firstName = firstName;   }    public String getLastName() {     return lastName;   }    public void setLastName(String lastName) {     this.lastName = lastName;   }  }  public class UserSetForm {    private Set<User> users = new HashSet<User>();      public UserSetForm(){     users.add(new User());     users.add(new User());     users.add(new User());   }    public Set<User> getUsers() {     return users;   }    public void setUsers(Set<User> users) {     this.users = users;   }  } 

Controller code:

@RequestMapping("test.do") public void test(UserSetForm userForm) {   for (User user : userForm.getUsers()) {     System.out.println(user.getFirstName() + " - " + user.getLastName());   } } 

JSP form code:

<form action="test.do" method="post">   <table>    <thead>      <tr>       <th>First Name</th>       <th>Last Name</th>      </tr>    </thead>    <tfoot>      <tr>       <td colspan="2"><input type="submit" value="Save" /></td>      </tr>    </tfoot>    <tbody>      <tr>       <td><input name="users[0].firstName" value="aaa" /></td>       <td><input name="users[0].lastName" value="bbb" /></td>      </tr>      <tr>       <td><input name="users[1].firstName" value="ccc" /></td>       <td><input name="users[1].lastName" value="ddd" /></td>      </tr>      <tr>       <td><input name="users[2].firstName" value="eee" /></td>       <td><input name="users[2].lastName" value="fff" /></td>      </tr>    </tbody>   </table> </form> 

Similar to List binding.

Note that if the maximum value of the tag is greater than the Set size, an exception occurs in org. springframework. beans. InvalidPropertyException. Therefore, it is inconvenient to use it. No solution is found for the moment. If some netizens know it, please reply and share your practices.

5. Map binding:

Map is the most flexible. It also needs to be bound to objects, rather than directly written in parameters of the Controller method.

Model Code:

public class User {    private String firstName;    private String lastName;    public String getFirstName() {     return firstName;   }    public void setFirstName(String firstName) {     this.firstName = firstName;   }    public String getLastName() {     return lastName;   }    public void setLastName(String lastName) {     this.lastName = lastName;   }  }  public class UserMapForm {    private Map<String, User> users;    public Map<String, User> getUsers() {     return users;   }    public void setUsers(Map<String, User> users) {     this.users = users;   }  } 

Controller code:

@RequestMapping("test.do") public void test(UserMapForm userForm) {   for (Map.Entry<String, User> entry : userForm.getUsers().entrySet()) {     System.out.println(entry.getKey() + ": " + entry.getValue().getFirstName() + " - " +                  entry.getValue().getLastName());   } } 

JSP form code:

<form action="test.do" method="post">   <table>    <thead>      <tr>       <th>First Name</th>       <th>Last Name</th>      </tr>    </thead>    <tfoot>      <tr>       <td colspan="2"><input type="submit" value="Save" /></td>      </tr>    </tfoot>    <tbody>      <tr>       <td><input name="users['x'].firstName" value="aaa" /></td>       <td><input name="users['x'].lastName" value="bbb" /></td>      </tr>      <tr>       <td><input name="users['y'].firstName" value="ccc" /></td>       <td><input name="users['y'].lastName" value="ddd" /></td>      </tr>      <tr>       <td><input name="users['z'].firstName" value="eee" /></td>       <td><input name="users['z'].lastName" value="fff" /></td>      </tr>    </tbody>   </table> </form> 

Print result:

x: aaa - bbb y: ccc - ddd z: eee - fff 

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.