UUid的生成和request的自动注入bean

package cn.itcast.tool.utils;

import java.util.Map;
import java.util.UUID;

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

public class CommonUtils {
    
    /**
     * 返回一个uuid,一般用来不重复的数
     * @return
     */
    public static String uuid(){
        return UUID.randomUUID().toString().replace("-", "").toUpperCase();
    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static <T> T toBean (Map datas,Class<T> clazz){
        /*
         * 依赖commons-beanutils
         */
        try {
            T bean=clazz.newInstance();
            ConvertUtils.register(new DateConverter(), java.util.Date.class);
            BeanUtils.populate(bean, datas);
            return bean;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } 
        
    }
}

 

package cn.itcast.tool.utils;

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

import org.apache.commons.beanutils.Converter;

public class DataConverter implements Converter{

    @SuppressWarnings({"unchecked","rawtypes"})
    public Object convert( Class type, Object value) {
        /* 判断类型是否为Date */
        if(type!=java.util.Date.class){
            return null;
        }
        /* 判断值是否为String类型 */
        if(!(value instanceof String)){
            return null;
        }
        
        String s=(String)value;
        
        /* 把字符串转换成Date类型  */
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

}

 

posted @ 2016-10-19 14:26  guodaxia  阅读(356)  评论(0编辑  收藏  举报