Struts2 自定义全局转化器(Date与Timestamp)

采用struts2作为控制层时,客户端和服务器端对日期和时间戳的转换。在这里我们用全局转换器。

1.在源路径下建立xwork-conversion.properties文件,文件内容:

例子:

      java.util.Date=com...DateConverter(转化器类的路径)
      java.sql.Timestamp=com...TimestampConverter(转化器类的路径)

2.基于struts的自定义转换器继承StrutsTypeConverter,具体代码:

 

   日期型:

public class DateConverter extends StrutsTypeConverter {

	public Object convertFromString(Map map, String as[], Class class1) {
		return parseStringToDate(as[0]);
	}

	public String convertToString(Map map, Object obj) {
		String s = null;
		if (obj instanceof Date)
			s = dateTimeFormat.format(obj);
		return s;
	}

	private Date parseStringToDate(Object dateString) {
		Date date = null;
		if (dateString instanceof String)
			try {
				if(((String) dateString).trim().length()>10){
					date = dateTimeFormat.parse((String) dateString);// 日期解析不行,就用日期时间解析
				}else{
					date = dateFormat.parse((String) dateString);// 只是日期解析
				}
			} catch (ParseException p) {
				throw new XWorkException(
						"两种yyyy-MM-dd与yyyy-MM-dd HH:mm:ss都解析不了,时间参数为"
								+ dateString, p);
			}
		return date;
	}

	private static final SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd");

	private static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

}

   时间戳

 

public class TimestampConverter extends StrutsTypeConverter {

    public Object convertFromString(Map map, String as[], Class class1) {
        return parseStringToTimestamp(as[0]);
    }

    public String convertToString(Map map, Object obj) {
        String s = null;
        if (obj instanceof Timestamp) {
            String s1 = obj.toString();
            s = s1.substring(0, 19);
        }
        return s;
    }

    private Timestamp parseStringToTimestamp(Object obj) {
        Timestamp timestamp = null;
        if (obj instanceof String)
            try {
                timestamp = Timestamp.valueOf((String) obj);
            }
            catch (Exception exception) {
                throw new XWorkException("Could not parse Timestamp", exception);
            }
        return timestamp;
    }
}

 

这样就实现了自定义的全局转换器。主要是重写convertFromString和convertToString这两方法。

你可能感兴趣的:(Timestamp)