STRUTS2 Basic Learning (iv)-type converter

Source: Internet
Author: User

I. Custom Converters 1. Overview

STRUTS2 provides a generic type converter that can be used for conversions of common data types, but you need a custom converter if the target type is a special type. STRUTS2 type converters are actually implemented based on OGNL, and in OGNL projects there is a TypeConverter interface where custom type converters must implement
Ongl. TypeConverter.

2. Writing a type converter

(1) Implement TypeConverter interface, implement a method

    Public Object Convertvalue (map<string, object> context, object target, Member Member, String PropertyName, Object va Lue, Class ToType);

(2) Inheriting the Defaulttypeconverter class, overriding a method

Public Object convertvalue (map<string,object> context,object value,class totype)

(3) Inheriting the Strutstypeconverter class rewrite two methods

Public Object convertfromstring (Map context,string[] Values,class toclass)
Public String converttostring (Map context,object o)

A property of type Java.util.Date can receive a request parameter value in the format of 2009-07-20. But if we need to receive the request parameter in the format 20091221, we must define the type converter, otherwise struts2 cannot complete the type conversion automatically.

The first type: inheriting the Defaluttypeconverter class

public class Dateconvert extends defaulttypeconverter{@Overridepublic Object convertvalue (map<string,object> Context,object Value,class totype) {SimpleDateFormat SDF = new SimpleDateFormat ("YyyyMMdd"); try{//string--->Dateif (ToType = = Date.class) {string[] params = (string[]) Value;return sdf.parseobject (Params[0]);} else if (ToType = = string.class) {//date--->stringdate date = (date) Value;return Sdf.format (date);}} catch (ParseException e) {e.printstacktrace ();} Return Super.convertvalue (Context,value,totype);}}

The second type of inheritance Strutstypeconverter class

public class DateConvert2 extends strutstypeconverter{private simpledateformat sdf = new SimpleDateFormat ("YyyyMMdd"); /string--->date@overridepublic Object convertfromstring (Map context,string[] Values,class toclass) {if (ToClass = = Date.class) {try{string date = Values[0];return sdf.parse (date);} catch (ParseException e) {e.printstacktrace ();}} return null;} Date--->string@overridepublic String converttostring (Map context,object o) {if (o instanceof Date) {return Sdf.format (o);} return null;}}

3. Register the type converter

(1) Partial registration

is for a field in the form to take effect. It is divided into two kinds: attribute driving mode and model driving mode.

Property-driven approach
Note: Create a file under the package where the action is located , the file is in the format: Action class name-conversion.properties file, which configures the field to transform data and the corresponding converter full path. Birthday=com.kiwi.convert.dateconvert2

Model-driven approach

Note: Create a file under the package where the entity class is located , the file is in the format: entity class name-conversion.properties file, which configures the field to transform data and the corresponding converter full path.

(2) Global registration

All date types for the entire project will take effect.

In the SRC directory, create a xwork-conversion.properties

Example: Java.util.date=cn.itcast.demo3.mydateconverter

4. Error handling for type conversions

(1) When a type conversion error occurs, the result view of input type is not provided according to the information of the wrong error. You can configure the input results view in the <action> tab.
(2) If an error occurs when the Struts2 type converter performs a type conversion, the interceptor is responsible for encapsulating the corresponding error as a form field error (FIELDERROR) and putting the error information into Actioncontext.
(3) Using error handling in type conversions user-defined action must inherit actionsupport.
(4) In a custom type converter, an exception must be thrown that cannot be caught, Conversionerror handles the exception, and then goes to a logical view named input.
(5) In the action package, create a actionname.properties to configure the prompt in the local resource file

Invalid.fieldvalue. Property name = Error message

index.jsp

<S:formAction= "Personaction">            <S:textfieldlabel= "User name"name= "username"></S:textfield>        <S:textfieldlabel= "Password"name= "Password"></S:textfield>        <S:textfieldlabel= "Age"name= "Age"></S:textfield>        <S:textfieldlabel= "Birthday"name= "Birthday"></S:textfield>                <S:submitvalue= "Submit"></S:submit>    </S:form>
Struts.xml
<action name= "personaction"  class= "com.kiwi.action.PersonAction" ><result name= "Success" >/ Success.jsp</result><result name= "Input" >/index.jsp</result></action>

Results:

Struts2 Basic Learning (iv)-type converter

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.