在Struts中使用LazyValidatorForm处理List属性的问题
LazyValidatorForm中存在List属性的时候,目前在Struts 1.2.9的配置文件中无法配置List元素的类型,这样带来了两个问题:
1. Struts组装FormBean后,List里面的元素是DynaBean,使用BeanUtils.copyProperties从form复制到业务对象的时候,因为业务对象使用了List<T>这样的list元素,copyProperties就出错了。
2. 如果List的元素还嵌套有其他对象,如OrderItem里面还有一个Product的属性,在页面上使用的input元素,名字为product.id, 可以正常显示,但是表单提交的时候,Struts调用BeanUtils.populate 方法会报错,提示No bean specified。
第一个问题,可以覆盖List元素的set方法解决,遍历提交上来的List<DynaBean>对象,使用BeanUtils.copyProperties将dynaBean复制到对应的业务对象上面,虽然麻烦一点,也可以使用。
第二个问题中,如果对象不在List中,可以在LazyValidatorForm定义的时候声明一下对象的属性,但是List里面我就不知道如何处理了。
对于这两个问题,我查了一些资料,始终没有得到比较好的解决方法。最常用的方法是将List属性换成Array属性,这样就可以在LazyValidatorForm定义的时候声明Array元素的类型。
大家说说看,是否有更好的解决方法? Method[] methods = (Method[]) cache.get(target.getClass());
if (methods == null) {
methods = target.getClass().getMethods();
cache.put(target.getClass(), methods);
}
for (int i = 0; i < methods.length; i++) {
if (property.equalsIgnoreCase(methods[i].getName())) {
Class[] paramClass = methods[i].getParameterTypes();
if (paramClass.length == 1) {
try {
methods[i].invoke(target, new Object[] {value});
}
catch (IllegalArgumentException ille) {
throw ille;
}
catch (Exception ex) {
logger.error(ex);
}
}
}
}
}
public final static void populate(Object obj, Map map) {
Set s = map.entrySet();
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry me = (Map.Entry) it.next();
setValue(me.getKey().toString(), obj, me.getValue());
}
}
用的时候直接
BenUtils.populate(povo,form.getMap());