Struts2 type conversion

Source: Internet
Author: User

Struts2 supports some basic type conversions. If not, you can define some types of converters by yourself.

For example, to implement the following functions:

The input format of the birthday (Date type) is required to be the above. The format supported by Struts2 is "", so we need to write our own converter.

The implementation class can be as follows:

Import java. text. simpleDateFormat; import java. util. *; import org. apache. struts2.util. strutsTypeConverter; public class DateTypeConverter extends StrutsTypeConverter {// inherits StrutsTypeConverter @ Overridepublic Object convertFromString (Map arg0, String [] value, Class toType) {// convert to Date type SimpleDateFormat sf = new SimpleDateFormat ("yyyyMMdd"); String [] params = null; try {if (toType = Date. class) {params = (String []) value; return sf. parse (params [0]) ;}} catch (Exception e) {} return null ;}@ Overridepublic String convertToString (Map arg0, Object arg1) {// convert to String type return arg1.toString ();}}

It is defined as a local converter:

In the same-level directory of the action class, create a. properties file named "Action class name-conversion. propertites" and add a key-Value Pair named "key" and "converter class name ".

birthday=cn.ljf.DateTypeConverter

Defined as global:

Create a new. properties type file in the src directory, file name: xwork-conversion.propertites, and add a key-Value Pair named value with java. util. Date as the key

java.util.Date=cn.ljf.DateTypeConverter

Handle type conversion errors:

Is the error handling process of type conversion:

If an exception occurs during type conversion, the system's conversionError interceptor will handle the exception. After the exception is processed, the system returns the logic view named input. You can use <s: fielderror/> output error information in this view. Note that action should inherit ActionSupport.

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.