论坛首页 Java企业应用论坛

在Struts中使用LazyValidatorForm处理List属性的问题

浏览 4026 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-04-08  
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元素的类型。
大家说说看,是否有更好的解决方法?
   发表时间:2008-04-09  
难道没人碰到这样的问题吗?
还是我表达的不清楚。
0 请登录后投票
   发表时间:2008-04-09  
我遇到第二个问题,也没有解决方法。希望能在这里找到答案。
0 请登录后投票
   发表时间:2008-04-15  
第一:首先确定为要使用Form呢?
   如果不使用validate和form验证,那么就不要使用form了
手工实现动态form
使用装饰器模式
public class DynaForm{
HttpServletRequest request=null;
public DynaForm(HttpServlet request){
this.request=request;
}
public String getString(String name){
return request.getString(name);
}
getInt
getDouble
getDate
..............
第二:重写BeanUtil

/**
   * 设置一个对象属性的值
   *
   * @param property 属性名称
   * @param target 目标对象
   * @param value 属性值
   */
  public final static void setValue(String property, Object target,
                                    Object value) {
    property = "set" + property;
    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());
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics