STRUTS2 implement custom converters and global type converters

Source: Internet
Author: User
Tags dateformat

One of the fields in the action is birthday is the date type, and when we pass the value it must be written in 1999-01-01 it will be converted automatically, but there are times when the requirement is written as 19990101 so that no automatic type conversion is done by default. This allows us to write a custom type converter to implement the transformation requirements.

STRUTS2 has two types of converters:

Local: Working on an Action transformation type

To customize the type converter first:

public class Datetypeconverter extends Defaulttypeconverter {
	@Override the public
	Object Convertvalue (map< String, object> context, Object value, Class totype) {
		SimpleDateFormat DateFormat = new SimpleDateFormat ("YYYYMMD D ");
		try { 
			if (ToType = = Date.class) {//when the string is converted to the Date type
				string[] params = (string[)) value;// Request.getparametervalues () return 
				dateformat.parse (params[0]);
			else if (ToType = = String.class) {//when date is converted to a string,
				date date = (date) value;
				return Dateformat.format (date);
			}
		catch (ParseException e) {} return
		null;
	}
}

To register:

Create Helloworldaction-conversion.properties file helloworldaction is the action to be registered.

The content of the file is the content converter to which the property in the action is to be typed and only to:

Birthday=cn.test.type.converter.datetypeconverter

Global: Works on all action conversion types

Create a xwork-conversion.properties file under SRC

Content is: Java.util.date=cn.test.type.converter.datetypeconverter

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.