使用方:
//因为泛型的运行期擦除,List,Set,Map 都只支持String 类型 public void arr(int a, String b, int[] c, List<String> d, Set<String> e, Map<String, String> f) { OK(c); }
实现方式,在自己的MyController中:
/** * 覆盖父类的action参数注入方法,支持 数组,List,Set,Map传递 * @param beanClass * @param beanName * @param skipConvertError * @param <T> * @return */ public <T> T getBean(Class<T> beanClass, String beanName, boolean skipConvertError) { HttpServletRequest request = getRequest(); if (beanClass.isArray()) return createParam2Array(beanClass, beanName, request); if (beanClass.isInterface()) return createParam2Interface(beanClass, beanName, request); return super.getBean(beanClass, beanName, skipConvertError); }
其它工具方法:
protected static <T> T createParam2Array(Class<T> beanClass, String beanName, HttpServletRequest request) { String[] vs = getParamValues(beanName, request); if (vs == null || vs.length == 0) return null; Class elemType = beanClass.getComponentType(); Object p = Array.newInstance(elemType, vs.length); for (int i = 0; i < vs.length; i++) { Object elmv = cover2Type(vs[i].trim(), elemType); Array.set(p, i, elmv); } return (T) p; } protected static <T> T createParam2Interface(Class<T> beanClass, String beanName, HttpServletRequest request) { Object p = null; if(beanClass == List.class || beanClass == Set.class){ String[] vs = getParamValues(beanName, request); if (vs == null || vs.length == 0) return null; if (beanClass == List.class) { p = new ArrayList(); List pp = (List) p; for (int i = 0; i < vs.length; i++) { pp.add(vs[i].trim()); } } if (beanClass == Set.class) { p = new HashSet(); Set pp = (Set) p; for (int i = 0; i < vs.length; i++) { pp.add(vs[i].trim()); } } }else if (beanClass == Map.class) { String json = request.getParameter(beanName); p = JSON.parseObject(json, LinkedHashMap.class); } return (T) p; } protected static String[] getParamValues(String pname, HttpServletRequest request) { String[] vs = request.getParameterValues(pname); if (vs == null || vs.length == 0) { //兼容ajax调用时的数组方式 vs = request.getParameterValues(pname + "[]"); } else { vs = vs[0].split(","); } if (vs == null || vs.length == 0) return null; return vs; } protected static Object cover2Type(String v, Class objType) { if (objType == int.class || objType == Integer.class) return Integer.valueOf(v); if (objType == boolean.class || objType == Boolean.class) return Boolean.valueOf(v); if (objType == Date.class) return new Date(v); if (objType == float.class || objType == Float.class) return Float.valueOf(v); if (objType == long.class || objType == Long.class) return Long.valueOf(v); if (objType == double.class || objType == Double.class) return Double.valueOf(v); if (objType == BigDecimal.class) return new BigDecimal(v); if (objType == BigInteger.class) return new BigInteger(v); return null; }
原有的贴子其实可以随时修改,也可以删除