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

你可能感兴趣的:(Mbean)