现在的位置: 首页 > 综合 > 正文

struts1.x 中提交form[]表单数组以及后台解析

2012年11月05日 ⁄ 综合 ⁄ 共 1219字 ⁄ 字号 评论关闭

entity中这样写:

private String xxx; //setXxx、getXxx方法

...

form中可以这样写:

private String[] xxx; //setXxx、getXxx方法

...

提交到后台之后这样解析:

public static synchronized Collection getCollection(HttpServletRequest parameters,
	      Class entity) throws
	      InvocationTargetException,
	      InstantiationException,
	      IllegalAccessException {
	    Object dto = entity.newInstance();
	    PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(dto);

	    String propName = null;
        int length = 0;
        String[] tmp = null;
        for(int i = 0; i < origDescriptors.length; i++){
          propName = origDescriptors[i].getName();
          //属性不能是class
          if(!"class".equals(propName)){
            tmp = parameters.getParameterValues(propName);
            if(null != tmp){
              length = tmp.length;
              break;
            }
          }
        }

	    Collection result = new ArrayList();
	    for (int j = 0; j < length; j++) {
	      Object item = entity.newInstance();
	      for (int i = 0; i < origDescriptors.length; i++) {
	        if (origDescriptors[i].getReadMethod() == null) {
	          if (log.isTraceEnabled()) {
	            log.trace("-->No getter on JavaBean for " + origDescriptors[i].getName() + ", skipping");
	          }
	          continue;
	        }
	        String name = origDescriptors[i].getName();
	        if ("class".equals(name)) {
	          continue; // No point in trying to set an object's class
	        }
            Object value = null;
            tmp =  parameters.getParameterValues(name);
            if(null != tmp)
              value = tmp[j];
            BeanUtils.copyProperty(item, name, value);
	      }
	      result.add(item);
	    }
	    return result;
	  }

然后根据生成的集合进行后台数据处理即可。

抱歉!评论已关闭.