Posted on 2009-03-24 12:26
sailor 閱讀(1028)
評(píng)論(0) 編輯 收藏 所屬分類:
心得體會(huì) 、
java
經(jīng)過(guò)一天測(cè)試,終于實(shí)現(xiàn)了BeanUtils從String類型到Timestamp成功轉(zhuǎn)換。底層是如何實(shí)現(xiàn)的,還沒(méi)徹底了解,先將解決方案記錄下來(lái),以后再去看底層如何實(shí)現(xiàn)。
1、寫一個(gè)日期轉(zhuǎn)換器,這個(gè)轉(zhuǎn)換器實(shí)現(xiàn)了Converter接口
1
public class DateConvert implements Converter
{
2
private Logger log = Logger.getLogger(DateConvert.class);
3
static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
4
private String datePattern = "yyyy-MM-dd";
5
6
public DateConvert()
{
7
8
}
9
10
public DateConvert(String datePattern)
11
{
12
this.datePattern = datePattern;
13
}
14
15
/** *//**
16
* @type 需要被轉(zhuǎn)換的類型
17
* @value 被轉(zhuǎn)換的值
18
*/
19
public Object convert(Class type, Object value)
{
20
21
if(value==null)
22
return null;
23
24
if(((String)value).trim().length()==0)
25
return null;
26
27
if(value instanceof String)
{
28
try
{
29
//解析接收到字符串
30
return TimestampUtil.parseTimestamp((String)value,datePattern); //自己寫的封裝,得到一個(gè)Timestamp實(shí)例
31
32
} catch (Exception ex)
{
33
//發(fā)生解析異常
34
throw new ConversionException("輸入的日期類型不合乎" + datePattern + "格式" + value.getClass());
35
}
36
} else
{
37
//其他異常
38
throw new ConversionException("輸入的不是字符類型" + value.getClass());
39
}
40
}
41
}
2、自己重寫了一個(gè)BeanUtil,用于實(shí)現(xiàn)拷貝request傳遞來(lái)的參數(shù)到Model里面,里面注冊(cè)了一個(gè)日期處理監(jiān)聽(tīng),這個(gè)組件還有待改進(jìn)
1
public class BeanUtil
{
2
3
public void copyBean()
{};
4
5
/** *//**
6
* 將request里的參數(shù)封裝到一個(gè)Bean。如果bean里面有日期型,只是java.sql.Date,java.sql.TimeStamp類型
7
* @param request
8
* @param bean
9
* @throws IllegalAccessException
10
* @throws InvocationTargetException
11
*/
12
public static void copyRequestPrameterToModel(HttpServletRequest request, Object bean) throws IllegalAccessException, InvocationTargetException
{
13
Map map = getRequestPrameters(request);
14
15
if(map == null)
16
return ;
17
18
ConvertUtils.register(new DateConvert(), java.sql.Timestamp.class); //注冊(cè)監(jiān)聽(tīng)
19
BeanUtils.populate(bean, map);
20
};
21
22
/** *//**
23
* 從request中取出key和value封裝到Map里
24
* @param request
25
* @return
26
*/
27
private static Map<String,Object> getRequestPrameters(HttpServletRequest request)
28
{
29
Map<String,Object> map = new HashMap<String,Object>();
30
31
Enumeration enuma = request.getParameterNames();
32
while(enuma.hasMoreElements())
33
{
34
String key = (String)enuma.nextElement();
35
36
String value = (String)request.getParameter(key); //獲取value
37
38
//如果值為空的話,就不插入map里
39
if(null == value || "".equals(value))
40
{
41
continue;
42
}
43
44
map.put(key, request.getParameter(key));
45
}
46
47
return map;
48
}
49
}