从前台请求中通过反射获取多条同名参数并封装返回相应VoList
第一次发贴,请大家多多指教!
场景:前台(Struts1)中批量修改列表信息
问题:列表中相同域的表单名都相同,这个时候需要后台中获取所有列表中的信息,封装VO然后保存。如何获取相应的请求并封装成VoList返回是我们要想办法做的事情!
例子:
其中姓名,年龄,QQ都可以让用户直接编辑修改,同一列(比如姓名列的张三,李四)对应表单的name都相同,页面POST提交。
?
为了解决这个问题,用反射写了一个工具类,如下!但感觉还可以优化,大家帮忙提一下意见!代码如下:
?
package com.eshore.dakar.common;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import javax.servlet.http.HttpServletRequest;@SuppressWarnings("unchecked")public class RequestUtil {/** * 把页面请求参数(多条参数名一样),转成voList * * @param request * http请求 * @param voClass * 需要转成的VO的class * @return * @throws SecurityException * @throws NoSuchMethodException * @throws InstantiationException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws NoSuchFieldException */public static List getVoList(HttpServletRequest request, Class voClass)throws SecurityException, NoSuchMethodException,InstantiationException, IllegalAccessException,IllegalArgumentException, InvocationTargetException, NoSuchFieldException {Map resultMap = new HashMap();if (request == null) {return new ArrayList();}if (voClass == null) {return new ArrayList();}// Vo类里的所有属性List<String> fieldNames = getFieldNames(voClass);// 页面带过来的所有参数/值Map parameterMap = request.getParameterMap();// 页面带过来的所有参数名Set keySet = parameterMap.keySet();for (Iterator it = keySet.iterator(); it.hasNext();) {String fieldName = (String) it.next();// 实体名// vo中存在的属性名if (fieldNames.contains(fieldName)) {StringBuffer setMethodName = new StringBuffer();setMethodName.append("set");setMethodName.append(fieldName.substring(0, 1).toUpperCase());setMethodName.append(fieldName.substring(1));//获取Vo类的Set方法Field field = voClass.getDeclaredField(fieldName);Method setMethod = voClass.getMethod(setMethodName.toString(), field.getType());String[] strValues = (String[]) parameterMap.get(fieldName);for (int i = 0; i < strValues.length; i++) {if (!resultMap.containsKey(String.valueOf(i))) {Object voInstance = voClass.newInstance();resultMap.put(String.valueOf(i), voInstance);}Object existVoinstance = resultMap.get(String.valueOf(i));// 调用Vo的get方法设置setMethod.invoke(existVoinstance, strValues[i]);}}}return new ArrayList(resultMap.values());}/** * 获取某个类的所有属性名 * * @param voClass * @return */public static List<String> getFieldNames(Class voClass) {List<String> result = new ArrayList<String>();if (voClass == null) {return result;}Field[] fields = voClass.getDeclaredFields();for (int i = 0; i < fields.length; i++) {result.add(fields[i].getName());}return result;}}?
?
?
?
?