Posted on 2009-03-24 12:26
sailor 阅读(1031)
评论(0) 编辑 收藏 所属分类:
心得体会 、
java
经过一天测试,终于实现了BeanUtils从String类型到Timestamp成功转换。底层是如何实现的,还没彻底了解,先将解决方案记录下来,以后再去看底层如何实现。
1、写一个日期转换器,这个转换器实现了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 需要被转换的类型
17
* @value 被转换的值
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); //自己写的封装,得到一个Timestamp实例
31
32
} catch (Exception ex)
{
33
//发生解析异常
34
throw new ConversionException("输入的日期类型不合乎" + datePattern + "格式" + value.getClass());
35
}
36
} else
{
37
//其他异常
38
throw new ConversionException("输入的不是字符类型" + value.getClass());
39
}
40
}
41
}
2、自己重写了一个BeanUtil,用于实现拷贝request传递来的参数到Model里面,里面注册了一个日期处理监听,这个组件还有待改进
1
public class BeanUtil
{
2
3
public void copyBean()
{};
4
5
/** *//**
6
* 将request里的参数封装到一个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); //注册监听
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
}