传智Struts2笔记(9)类型转换器
自定义类型转换器
java.util.Date类型的属性可以接收格式为2009-07-20的请求参数值。但如果我们需要接收格式为20091221的请求参数,我们必须定义类型转换器,否则struts2无法自动完成类型转换。
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;// Request.getParameterValues() return dateFormat.parse(params[0]);}else if(toType == String.class){//当Date转换成字符串时Date date = (Date) value;return dateFormat.format(date);}} catch (ParseException e) {}return null;}}