Type converters are divided into global type converters and local type converters. Global type conversions work for all actions, while local type converters target an action
One, global type converter. Convert string x, Y to point
login.jsp page
<S:formMethod= "POST"Action= "Test"> <S:textfieldname= "username"label= "Account"></S:textfield> <S:passwordname= "Password"label= "Password"></S:password> <S:textfieldname= "point"label= "coordinates"></S:textfield> <S:submit></S:submit> </S:form>
Defining entity Classes
Packagemodels; Public classPoint {Private intx; Private inty; Public intGetX () {returnx; } Public voidSetX (intx) { This. x =x; } Public intGetY () {returny; } Public voidSety (inty) { This. y =y; } PublicPoint () {} PublicPoint (intXinty) { This. x =x; This. y =y; } }
Point.java
Packagemodels; Public classUser {PrivateString username; PrivateString password; PrivatePoint Point ; PublicString GetUserName () {returnusername; } Public voidSetusername (String username) { This. Username =username; } PublicString GetPassword () {returnpassword; } Public voidSetPassword (String password) { This. Password =password; } PublicPoint GetPoint () {returnPoint ; } Public voidsetpoint (Point point) { This. Point =Point ; } }
User.java
Defining the Action Class
PackageAction;ImportCom.opensymphony.xwork2.ModelDriven;Importmodels. Point;Importmodels. User; Public classTestImplementsModeldriven<user> { PrivateUser user=NewUser (); PublicString Execute () {System.out.println (User.getpoint ()); return"Success"; } PublicUser Getmodel () {//TODO auto-generated Method Stub returnuser; }}
Test.java
Defining a type converter
PackageCoverter;ImportJava.util.Map;Importmodels. Point;ImportOrg.apache.struts2.util.StrutsTypeConverter; Public classPointconverterextendsstrutstypeconverter{@Override PublicObject convertfromstring (Map arg0, string[] arg1, Class arg2) { point point=NULL; if(arg1.length>0) { point=NewPoint (); String[] Cods=arg1[0].split (","); Point.setx (Integer.parseint (cods[0])); Point.sety (Integer.parseint (cods[1])); } returnPoint ; } @Override PublicString converttostring (Map arg0, Object arg1) { point point=(point) arg1; returnPoint.getx () + "," +point.gety (); }}
Pointconverter.java
Create a new xwork-conversion.properties file under SRC with the following content:
Models. Point=coverter. Pointconverter
The preceding is the class that requires the type conversion, followed by the converter
STRUTS2 type converter