类型转换
(来自尚学堂)
a) 默认转换
i. 日期处理
b) 写自己的转换器:
public class MyPointConverter extends DefaultTypeConverter{
@Override
public Object convertValue(Object value, Class toType) {
if(toType == Point.class) {
Point p = new Point();
String[] strs = (String[])value;
String[] xy = strs[0].split(",");
p.x = Integer.parseInt(xy[0]);
p.y = Integer.parseInt(xy[1]);
return p;
}
if(toType == String.class) {
return value.toString();
}
return super.convertValue(value, toType);
}
}
public class MyPointConverter extends StrutsTypeConverter{
@Override
public Object convertFromString(Map context, String[] values, Class toClass) {
Point p = new Point();
String[] strs = (String[])values;
String[] xy = strs[0].split(",");
p.x = Integer.parseInt(xy[0]);
p.y = Integer.parseInt(xy[1]);
return p;
}
@Override
public String convertToString(Map context, Object o) {
// TODO Auto-generated method stub
return o.toString();
}
}
c) 三种注册方式:
i. 局部:XXXAction-conversion.properties
1. p(属性名称) = converter
ii. 全局:xwork-conversion.properties
1. com.xxx.XXX(类名)= converter
iii. Annotation
d) 如果遇到非常麻烦的映射转换
i. request.setAttribute();
ii. session