页面表单提交到servlet后转为对象工具类

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







  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值