`
把阳光剪成雨Java
  • 浏览: 24138 次
  • 性别: Icon_minigender_1
  • 来自: 长春
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
WebUtils,将form表单数据封装到formbean中,生成全球唯一ID,将formbean中的属性值拷贝到User里
package cn.utils;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import cn.web.formbean.FormBean;

public class WebUtils {
	public static <T> T request2bean(HttpServletRequest request, Class<T> type) {
		T bean;
		try {
			bean = type.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		Enumeration en = request.getParameterNames();
		while (en.hasMoreElements()) {
			String name = (String) en.nextElement();
			String value = request.getParameter(name);
			try {
				BeanUtils.setProperty(bean, name, value);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return bean;
	}

	public static void copyBean(Object dest, Object src) {
		ConvertUtils.register(new Converter() {
			@Override
			public Object convert(Class type, Object value) {
				if (value == null)
					return null;
				String str = (String) value;
				if (str.trim().equals(""))
					return null;
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				try {
					return df.parse(str.trim());
				} catch (ParseException e) {
					throw new RuntimeException();
				}
			}
		}, Date.class);
		try {
			BeanUtils.copyProperties(dest, src);
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	public static String generateID() {
		return UUID.randomUUID().toString();
	}
}
自定义类型转换器 string,date
public class DateConverter extends DefaultTypeConverter {
                @Override  public Object convertValue(Map context, Object value, Class toType) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		try { 
			if(toType == Date.class){//当字符串向Date类型转换时
				String[] params = (String[]) value;		
				return dateFormat.parse(params[0]);
			}else if(toType == String.class){//当Date转换成字符串时
				Date date = (Date) value;
				return dateFormat.format(date);
			}
		} catch (ParseException e) {}
		return null;
	}
}
Global site tag (gtag.js) - Google Analytics