011 - 自定义converter

1. 自定义converter

1) 从DefaultTypeConverter继承,重写convertValue()方法

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);

    }

 

}

 

 

 

2) 从StrutsTypeConverter继承,重写convertFromString()和convertToString()方法

 

//MyPointConverter.java

 

 

public class MyPointConverter extends StrutsTypeConverter{

 

     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;

     }

 

 

    public String convertToString(Map context, Object o) {

           return o.toString();

    }

 

} 

 

 

2. 注册方式:

   1)局部:XxxAction-conversion.properties(与XxxAction放一起,-conversion.properties是固定的)

   内容:p(Action的属性名称) =  converter    (如:p=edu.ray.converter.MyConverter)

      

   2)全局:xwork-conversion.properties(放到src目录下,同样,-conversion.properties是固定的)

内容:com.xxx.XXX(类名)= converter  (如:edu.ray.model.Point=edu.ray.converter.MyConverter)

 

 

3. 参数传递

 

如:

Map :   userMap['key']=value

List  :   users[0].name=XXX

Point:   p=2,3 & p=3,5

 

 

你可能感兴趣的:(Converter)