Custom STRUTS2 type Converters

Source: Internet
Author: User

One, custom type converter

1, write a class, inherit Com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter

2, covering out the public Object convertvalue (map<string, object> context, Object Value,class ToType)

CONTEXT:OGNL The context of an expression

Value: The actual value. The user input is a string, but he is an array of string.

totype: Target type

PUBLIC&NBSP;CLASS&NBSP;DATECONVERTOR&NBSP;EXTENDS&NBSP;DEFAULTTYPECONVERTER&NBSP;{/*&NBSP;CONTEXT:OGNL the context of an expression  value: The values entered by the user (  when data is saved) or properties in the model. The value entered by the user is a String array  totype: The target type  */@Overridepublic  object convertvalue (map<string,  Object> context, object value,class totype)  {    dateformat  df = new simpledateformat ("Yyyy/mm/dd");     if (ToType==Date.class) {         String strValue =  ((string[]) value) [0];     try {        return df.parse (StrValue);          } catch  (parseexception e)  {         throw new runtimeexception (e);         }    }else{        date dvalue =  (Date) value;        return  Df.format (dvalue);         }    }}

3. Register type Converter

3.1 Local type converter: Valid only for the current action

Practice: In the same package as the action class, a configuration file named "Action class name-conversion.properties" is created,

File, add the following: field to verify = Full class name of validator

Birthday=cn.itcast.convertor.dateconvertor

3.2 Global type converter: valid for all action

Practice: Under the Web-inf/classes directory, create a configuration file called "Xwork-conversion.properties",

The following is added to the file: Full name of the target type = Full class name of the validator

Java.util.date=cn.itcast.convertor.dateconvertor

Note: If the conversion fails, the STRUTS2 framework looks for the Name=input results page


Custom STRUTS2 type Converters

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.