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