The sharing of form data processing techniques based on custom editor in Spring MVC _java

Source: Internet
Author: User

Object-oriented programming is a great way to help programmers spend their time managing data. In the process of web development based on spring MVC, the data submitted by the form can be managed through object mapping, rather than being extracted from the request in one place. In addition, this feature supports mapping of basic data types. such as in, long, float, and so on. This allows us to be free from the traditional single string type. However, the application is flexible. Our demand for data is ever-changing. There are times when we need to be compatible with the data in the form.

For example, date format compatibility:

China's date tagging habits adopt YYYY-MM-DD format, Europe and the United States used to use MM/DD/YYYY. Although both formats are tagging methods for dates, we often have to do cumbersome conversions to achieve compatibility.

For example, price compatibility:

Price is nothing more than a string of numbers, we often use is 0.00 this form of expression, and for the larger price we are also accustomed to using 0,000.00 such a comma-separated price expression form.

In fact, this problem has been taken into account in spring MVC, where you can register an editor at the time of initialization of the binding (Controller). When the data submitted by the form is mapped to a particular type (even a specific parameter), it can be converted in a customized way. (in addition to the data transmitted in binary mode, we generally think that all incoming parameters, regardless of what the content, are considered to be strings)

Now I'm inventing a demand:

I have a form where I need to fill in the username, birthday and points. This represents the string type, the date type, and the long type, respectively. The following are the contents of the form:

Copy Code code as follows:

<form action= "getobj.do" method= "POST" >
<table>
<tr>
<td> User name:</td>
<td><input type= "text" name= "UserName" value= "name Test"/></td>
<td>* Normal String </td>
</tr>
<tr>
<td> Birthday:</td>
<td><input type= "text" name= "Birthday" value= "2013-3-7"/></td>
<td>* support format: YYYY-MM-DD or mm/dd/yyyy</td>
</tr>
<tr>
<td> Integral:</td>
<td><input type= "text" name= "score" value= "1,000"/></td>
<td>* supports either pure digits or comma-delimited numbers </td>
</tr>
<tr>
&LT;TD colspan= "3" ><input type= "Submit" value= "submitted"/></td>
</tr>
</table>
</form>

Here, according to the form, we map the following form object, where the property name of the object is consistent with the field name of the form above:
Copy Code code as follows:

Package BLOG.CSDN.NET.CHAIJUNKUN.FORMOBJS;

Import Java.util.Date;

public class UserInfo {

Private String UserName;

Private Date birthday;

Private Long score;

Getters and setters ...

}


So we want to receive such a form of data, you can write a way to deal with the form:
Copy Code code as follows:

Package Blog.csdn.net.chaijunkun.controller;

Import Java.util.Map;

Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import Org.apache.log4j.Logger;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;

Import Blog.csdn.net.chaijunkun.formObjs.UserInfo;

@Controller
public class Objcontroller {

private static Logger logger= Logger.getlogger (objcontroller.class);

Public Objcontroller () {
Logger.info ("Object map controller initialization");
}

@RequestMapping (value= "/getobj.do")
Public String ModifyUser (HttpServletRequest request,
HttpServletResponse response,map<string, object> model,
UserInfo UserInfo) {
Logger.info ("Collect object Information");
Model.put ("UserInfo", userInfo);
return "user";
}

}


If this is the only way to write, of course, you can't do multiple format compatibility. We need to write a format-compatible editor for dates and long. The editor needs to inherit at least from the class: Java.beans.PropertyEditorSupport. Of course, you can also inherit some of the editors that spring has built into, such as: Org.springframework.beans.propertyeditors.CustomNumberEditor, which is specifically used to handle numeric conversions. Whichever is inherited, the method is the same:

First step: Rewrite the public void Setastext (String text) method;

Step two: Write the converted data call SetValue (Object obj).

Let's first implement a date-compatible editor:

Copy Code code as follows:

Package blog.csdn.net.chaijunkun.editors;

Import Java.beans.PropertyEditorSupport;
Import java.text.ParseException;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;

public class Mydateeditor extends PropertyEditorSupport {

@Override
/**
* Text is the data content that the form passes in
*/
public void Setastext (String text) {
Date value= null;
SimpleDateFormat sdf= new SimpleDateFormat ();
Sdf.applypattern ("Yyyy-mm-dd");
try{
value= sdf.parse (text);
}catch (ParseException E1) {
Sdf.applypattern ("mm/dd/yyyy");
try {
value= sdf.parse (text);
catch (parseexception E2) {
value= null;
}
}
This step writes the converted data to the properties of the object map
SetValue (value);
}

}


And then we'll write an editor for long, which can support numeric expressions with commas and no comma separated:
Copy Code code as follows:

Package blog.csdn.net.chaijunkun.editors;

Import Org.springframework.beans.propertyeditors.CustomNumberEditor;

public class Mylongeditor extends Customnumbereditor {

Public Mylongeditor () {
Super (Long.class, true);
}

@Override
public void Setastext (String text) {
if ((text== null) | | Text.trim (). Equals ("")) {
SetValue (NULL);
}else{
Long value= null;
try{
Try the conversion in the standard number format
value= Long.parselong (text);
}catch (NumberFormatException e) {
Try to remove the comma and then convert it
text= text.replace (",", "");
value= Long.parselong (text);
}
Returns the value to the mapped property after it has been turned.
SetValue (value);
}
}

}


Okay, so these two editors are written, how do you make them work? This requires adding a binding method to the Data transformation in controller:
Copy Code code as follows:

@InitBinder
public void Initbinder (HttpServletRequest request, Servletrequestdatabinder Binder) {
Binder.registercustomeditor (Date.class, New Mydateeditor ());
Binder.registercustomeditor (Long.class, New Mylongeditor ());
}

The code above is: When the form data is received, Spring discovers that the parameter name can correspond to the object attribute, and the conversion type is exactly the same as the one registered in the preceding code, the data content is converted according to the specified editor.

Let's try this:

As shown in the following illustration:

Again, the data is correctly identified.

Through the above methods, we successfully compatible with a variety of data formats.

Written in the back:

In fact, for the date format, I started by trying to write the following code to achieve compatibility:

Copy Code code as follows:

@InitBinder
public void Initbinder (HttpServletRequest request, Servletrequestdatabinder Binder) {
Binder.registercustomeditor (Date.class, New Customdateeditor (New SimpleDateFormat ("Yyyy-mm-dd"), true);
Binder.registercustomeditor (Date.class, New Customdateeditor (New SimpleDateFormat ("Mm/dd/yyyy"), true);
}

I later found that this writing only supports MM/DD/YYYY format dates, and throws an exception after the date submitted in YYYY-MM-DD format. It seems that for the same type, only one editor can be registered in a controller, and the last one to be registered will work.

In addition, it was written at the beginning of the article that not only can you customize the editor according to your requirements by type, or even by a certain type of attribute, but it does not affect other properties of the same type. This is easy, there is an overloaded method in the Registercustomeditor method, and the second parameter can specify a specific property name. This makes it easy to control the granularity.

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.