使用BeanUtils时,Date类型值为空的解决方法

解决办法参考: http://hi.baidu.com/fcp_bd/blog/item/0e632783c08836a50cf4d2c4.html/cmtid/53484428cab979f399250ad7

org.apache.commons.beanutils.ConversionException: No value specified for 'Date'

package com.asl.cityu.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.commons.beanutils.Converter;

public class DateConvert implements Converter {
	private static String dateFormatStr = "yyyy/MM/dd";
	private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat(dateFormatStr);
	
	private static String dateLongFormatStr = dateFormatStr+" HH:mm:ss";
	private static SimpleDateFormat dateTimeLongFormat = new SimpleDateFormat(dateLongFormatStr);

	public Object convert(Class arg0, Object arg1) {
		System.out.println(arg1.getClass().getName()+"="+arg1.toString());
		String className = arg1.getClass().getName();
		//java.sql.Timestamp
		if ("java.sql.Timestamp".equalsIgnoreCase(className)) {
			try {
				SimpleDateFormat df = new SimpleDateFormat(dateFormatStr + " HH:mm:ss");
				return df.parse(dateTimeLongFormat.format(arg1));
			} catch (Exception e) {
				try {
					SimpleDateFormat df = new SimpleDateFormat(dateFormatStr);
					return df.parse(dateTimeFormat.format(arg1));
				} catch (ParseException ex) {
					e.printStackTrace();
					return null;
				}
			}
		}else{//java.util.Date,java.sql.Date
			String p = (String) arg1;
			if (p == null || p.trim().length() == 0) {
				return null;
			}
			try {
				SimpleDateFormat df = new SimpleDateFormat(dateFormatStr + " HH:mm:ss");
				return df.parse(p.trim());
			} catch (Exception e) {
				try {
					SimpleDateFormat df = new SimpleDateFormat(dateFormatStr);
					return df.parse(p.trim());
				} catch (ParseException ex) {
					e.printStackTrace();
					return null;
				}
			}
		}
	}
	
	public static String formatDateTime(Object obj) {
		if (obj != null)
			return dateTimeFormat.format(obj);
		else
			return "";
	}
	
	public static String formatLongDateTime(Object obj) {
		if (obj != null)
			return dateTimeLongFormat.format(obj);
		else
			return "";
	}

}








package com.asl.cityu.common;

import java.lang.reflect.InvocationTargetException;

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

public class ExtBeanUtils extends BeanUtils {
	static {
		ConvertUtils.register(new DateConvert(), java.util.Date.class);
		ConvertUtils.register(new DateConvert(), java.sql.Date.class);
		ConvertUtils.register(new DateConvert(), java.sql.Timestamp.class);
	}

	public static void copyProperties(Object dest, Object orig) {
		try {
			BeanUtils.copyProperties(dest, orig);
		} catch (IllegalAccessException ex) {
			ex.printStackTrace();
		} catch (InvocationTargetException ex) {
			ex.printStackTrace();
		}
	}
}



最后调用:
ExtBeanUtils.copyProperties(toObject, fromObject);

你可能感兴趣的:(使用BeanUtils时,Date类型值为空的解决方法)