request.getParameterMap()返回的是一个Map,这个map记录着页面所提交请求中的请求参数与参数值的映射关系。不能直接修改其中的值,可以将这个map复制到一个map 如果request.getParameterMap()的返回值是Map<String,String[]>形式: Map map = new HashMap(); java.util.Enumeration enum=this.getRequest().getParameterNames(); while(enum.hasMoreElements()){ String paramName=(String)enum.nextElement(); String[] values=request.getParameterValues(paramName); for(int i=0;i<values.length;i++){
map.put(paramName, values);
} }
//页面表单提交到servlet后转为对象工具类,创建该工具类要首先导入commons-beanutils-1.8.3.jar
/** * 工具 * @author WEI */ public class CommonUtils { /** * 返回一个不重复的字符串 * @return */ public static String uuid() { return UUID.randomUUID().toString().replace("-", "").toUpperCase(); } /** * 把map转换成对象 * @param map * @param clazz * @return * * 把Map转换成指定类型 */ @SuppressWarnings("rawtypes") public static <T> T toBean(Map map, Class<T> clazz) { try { /* * 1. 通过参数clazz创建实例 * 2. 使用BeanUtils.populate把map的数据封闭到bean中 */ T bean = clazz.newInstance(); //BeanUtils.populate()方法中,Converter这个居然只支持一些基本的类型,不支持Java.util.Date,需要重写转换器。 ConvertUtils.register(new DateConverter(), java.util.Date.class); BeanUtils.populate(bean, map); return bean; } catch(Exception e) { throw new RuntimeException(e); } } }
转换器如下:
/** * 把String转换成java.util.Date的类型转换器 * @author WEI */ public class DateConverter implements Converter{ @SuppressWarnings("rawtypes") public Object convert(Class type, Object value) { //如果要转换成值为null,那么直接返回null if(value == null) return null; //如果要转换的值不是String,那么就不转换了,直接返回 if(!(value instanceof String)) { return value; } String val = (String) value;//把值转换成String // 使用SimpleDateFormat进行转换 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { return sdf.parse(val); } catch (ParseException e) { throw new RuntimeException(e); } }