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);
}
}