STRUTS2 Custom Type Converters

Source: Internet
Author: User

First, what is the type converter for struts2?

The role of a type converter is to convert a string or string array parameter in a request to an object in the action.

Most of the time, the type converter provided by Struts2 and the OGNL type conversion mechanism are used to satisfy most types of conversion requirements. Such as:

Class User.java

 Packagemodels; Public classUser {PrivateString username; PrivateString password;  PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }}

Class Loginaction

 Packageactions;Importjava.util.List;Importmodels. User;ImportCom.opensymphony.xwork2.ActionSupport; Public classLoginactionextendsActionsupport {Privateuser User;  PublicUser GetUser () {returnuser; }     Public voidsetUser (user user) { This. user =user; } @Override PublicString Execute ()throwsException {if(GetUser (). GetUserName (). Equals ("Yangys")                && GetUser (). GetPassword (). Equals ("123")) {            returnSUCCESS; }        returnERROR; }}

login.jsp

<%@ Page Language="Java"ContentType="text/html; Charset=utf-8"pageencoding="UTF-8"%><%@taglib prefix="s"URI="/struts-tags"%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd "><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title><S:textname= "Login Page"></S:text></title></Head><Body>    <S:formAction= "Login">        <S:textfieldname= "User.username"Key= "username" />        <S:passwordname= "User.password"Key= "Password" />        <S:submitvalue= "Login" />    </S:form></Body></HTML>

Without any processing, user.username and User.password in the form can be mapped to the user object in Loginaction.

Note: Relevant getter and setter are required

Second, in special cases, this type of conversion can not meet the needs, such as the need to convert a complex string into an object.

If user input "huaihaizi,123" need to map Huaihaizi to username, map 123 to password. You need to provide a custom type converter and register it in STRUTS2 for the system to invoke and complete the type conversion.

To simulate this requirement, change the login.jsp to the following, using a user input box to enter the username password, separated by commas.

<%@ Page Language="Java"ContentType="text/html; Charset=utf-8"pageencoding="UTF-8"%><%@taglib prefix="s"URI="/struts-tags"%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd "><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><title><S:textname= "Login Page"></S:text></title></Head><Body>    <S:formAction= "Login">        <S:textfieldname= "User"Key= "User" />        <S:submitvalue= "Login" />    </S:form></Body></HTML>

User.java and Loginaction.java remain unchanged. In order to map the contents of the user input box to the username and password of the user object, you need to write a custom converter class. There is an Typeconvert interface in the OGNL project, which is the interface that the custom type converter must implement, which is defined as follows.

 Public Interface TypeConverter {    public  Object Convertvalue (Map context, Object target, Member Member,            String PropertyName, Object value, Class totype);}

Implementing a custom type converter must implement the above interface, but the interface is too complex, so OGNL provides implementation class Defaulttypeconverter, which is usually inherited and rewritten defaulttypeconverter Convertvalue () method to implement a custom type converter, such as the above requirements, you need to write Userconverter.java, the code is as follows:

 PackageConverters;ImportJava.util.Map;Importmodels. User;ImportOGNL. Defaulttypeconverter; Public classUserconverterextendsDefaulttypeconverter {@Override PublicObject Convertvalue (Map context, object value, Class totype) {if(ToType = = User.)class) {string[] params=(string[]) value; User User=NewUser (); User.setusername (params[0].split (",") [0]); User.setpassword (params[0].split (",") [1]); returnuser; } Else if(ToType = = String.class) {User User=(User) value; String userstring= "<" + user.getusername () + "," + user.getpassword () + ">"; returnuserstring; }        return NULL; }}

Here, the Convertvalue method is the execution of the type conversion logic, the parameter value is the pre-conversion value, ToType is the conversion of the target type, by judging the ToType to perform the direction of the transformation of the logic code. In this case, when Totype==user.class, the object that converts the page string to the User class, the page parameter is uniformly wrapped as a string array if it is a string, or a string array of length 1, due to the versatility of the page control parameters. For example, in this example, the input is "huaihaizi,123", then assign the Huaihaizi to the User object Username, assign 123 to the password of the user object, and return this user. Conversely, the user object's username and password are stitched together into a string return.

Three, STRUTS2 provides a strutstypeconverter abstract class, this class is a subclass of Defaulttypeconverter, the convertvalue of the two conversion direction split into two methods,

ConvertFromString (Map context,string[] Values,class toclass)

ConvertToString (Map context, Object O)

Logic is clearer and usage is consistent with defaulttypeconverter.

Thirdly, you can register this custom type converter by registering this custom type converter in the STRUTS2 project in three ways.

1. Register a local type converter, and the local type converter only works on the properties of an action

A local type converter adds a actionname-convertion.properties in the same directory as the action and adds a row of mapping relationships inside the <propName>=<ConverterClass>. In this example, add the Loginaction-convertion.properties file under the Lgoinaction.java package and add the User=converters to the file. Userconverter can be.

2. Register a global type converter, the global type converter will take effect for all action specific types of properties

Provide the xwork-convertion.properties file under the source code root path. and add <propType>=<ConverterClass> to the file. In this example, add the Xwork-convertion.properties file to the SRC directory and add the models.user=converters to the file. Userconverter can be.

3. Use JDK1.5 Annotations to register the type converter.

STRUTS2 Custom 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.