继承默认装换器的转换方式
package com.newtouch.struts2;import java.util.Map;import java.util.StringTokenizer;import com.newtouch.entity.User;import ognl.DefaultTypeConverter;public class DIYConvert extends DefaultTypeConverter { @SuppressWarnings("rawtypes") @Override public Object convertValue(Map context, Object value, Class toType) { if (User.class == toType) { String[] values = (String[]) value; StringTokenizer stringTokenizer = new StringTokenizer(values[0], ";"); String username = stringTokenizer.nextToken(); String password = stringTokenizer.nextToken(); User user = new User(); user.setPassword(password); user.setUsername(username); System.out.println(user); return user; } else if (String.class == toType) { User user = (User) value; String strinfo = user.getPassword() + user.getUsername(); return strinfo; } return null; }}
在配置文件中配置你要转换的对象以及转换器的路径
配置文件的名字规定为:acitionName-conversion.properties 且配置文件的路径是在当前action的包下
user=com.newtouch.struts2.DIYConvert
方式二:继承StrutsTypeConverter
package com.newtouch.struts2;import java.util.Map;import java.util.StringTokenizer;import org.apache.struts2.util.StrutsTypeConverter;import com.newtouch.entity.User;public class TheStrutsConversion extends StrutsTypeConverter { @Override public Object convertFromString(Map map, String[] as, Class class1) { System.out.println("convertopen"); String string = as[0]; StringTokenizer stringTokenizer = new StringTokenizer(string, ";"); User user = new User(); user.setUsername(stringTokenizer.nextToken()); user.setPassword(stringTokenizer.nextToken()); user.setAge(Integer.parseInt(stringTokenizer.nextToken())); return user; } @Override public String convertToString(Map map, Object obj) { System.out.println("tostring"); User user = (User) obj; String string = user.getUsername() + user.getPassword() + user.getAge(); return string; }}
配置文件同上
如果你要配置全局的转换器那么你的配置文件要放在src下且命名为xwork-conversion.properties
键为转换的类型的全路径,值为转换器的转换器的路径
com.newtouch.entity.User=com.newtouch.struts2.TheStrutsConversion