DWR中提交form的时候,数据都封装在了Map结构中。这样当提交的内容是数组的时候,就会产生问题。
例如当提交这样的内容的时候,就无法得到正确的数据:
<input type=checkbox name="c1">
<input type=checkbox name="c1">
<input type=checkbox name="c1">
因此用了一个方法来解决这个问题。在form 中,如果是数组类型的变量,那么必须使用 “变量_”的方式。
所以,上面的三个checkbox 就变成了这样子:
<input type=checkbox name="c1_1">
<input type=checkbox name="c1_2">
<input type=checkbox name="c1_3">
然后使用一个方法来处理一下DWR提交的Map:
public static Map transferDWRMap(Map dwrFormMap) {
Map treeMap = new java.util.TreeMap();
treeMap.putAll(dwrFormMap);
Map resultMap = new HashMap<String, Object>();
Set set = treeMap.keySet();
Iterator it = set.iterator();
while(it.hasNext()) {
String key = (String) it.next();
logger.debug("transferDWRMap key = " + key);
int index = key.indexOf("_");
if(index >= 0) {
String realKey = key.substring(0, index);
Object value = resultMap.get(realKey);
if(value != null) {
if(value instanceof List) {
((List)value).add(treeMap.get(key));
resultMap.put(realKey, value);
} else {
List valueList = new ArrayList();
valueList.add(value);
valueList.add(treeMap.get(key));
resultMap.put(realKey, valueList);
}
} else {
List valueList = new ArrayList();
valueList.add(treeMap.get(key));
resultMap.put(realKey, valueList);
}
} else {
resultMap.put(key, treeMap.get(key));
}
}
return resultMap;
}
下面的是测试类:
public void testTransferDWRMap() {
Map dwrFormMap = new HashMap();
dwrFormMap.put("id_1", "id_1_value");
dwrFormMap.put("id_2", "id_2_value");
dwrFormMap.put("id_3", "id_3_value");
dwrFormMap.put("id_4", "id_4_value");
dwrFormMap.put("name_1", "name_1_value");
dwrFormMap.put("name_2", "name_2_value");
dwrFormMap.put("name_3", "name_3_value");
dwrFormMap.put("name_4", "name_4_value");
dwrFormMap.put("newName", "tom");
Map resultMap = EShopUtil.transferDWRMap(dwrFormMap);
List idList = (List) resultMap.get("id");
assertEquals(4, idList.size());
int index = 1;
for(Object value : idList) {
String id = (String) value;
assertEquals("id_"+index+"_value", id);
index++;
}
List nameList = (List) resultMap.get("name");
assertEquals(4, nameList.size());
index = 1;
for(Object value : nameList) {
String id = (String) value;
assertEquals("name_"+index+"_value", id);
index++;
}
assertEquals("tom", resultMap.get("newName"));
}
public void testTransferDWRMap2() {
Map dwrFormMap = new HashMap();
dwrFormMap.put("id_1", "id_1_value");
dwrFormMap.put("name_1", "name_1_value");
dwrFormMap.put("newName", "tom");
Map resultMap = EShopUtil.transferDWRMap(dwrFormMap);
List idList = (List) resultMap.get("id");
assertEquals(1, idList.size());
int index = 1;
for(Object value : idList) {
String id = (String) value;
assertEquals("id_"+index+"_value", id);
index++;
}
List nameList = (List) resultMap.get("name");
assertEquals(1, nameList.size());
index = 1;
for(Object value : nameList) {
String id = (String) value;
assertEquals("name_"+index+"_value", id);
index++;
}
assertEquals("tom", resultMap.get("newName"));
}
所以,提交form的时候,只要保证数组的变量是“变量_”的形式就可以了,不是数组的变量不要带下划线。这样就减轻了DWR的提交form的处理。