天天看點

Struts2自定義日期轉換器

1.日期格式轉換器

自定義日期格式轉換器,可以動态調整日期格式,并更新到資料庫。

/**
 * 儲存日期格式的基礎類。
 *
 * @author daichen
 *
 */
public class DateConverter extends StrutsTypeConverter {
   
    /**
     * 記憶體中的日期格式
     */
    private String format;
   
    /**
     * 可以從資料庫中加載日期格式
     */
    @PostConstruct
    public void loadFormat() {
    format = "yyyy-MM-dd";
    }
   
    @SuppressWarnings("rawtypes")
    @Override
    public Object convertFromString(Map context,String[] values, Class toClass) {
    // Pre-validate
        if (ArrayUtils.isEmpty(values) ||StringUtils.isEmpty(values[0])) {   
            return null;   
        }
       
        Date date = null;
        try {
            date = new SimpleDateFormat(format).parse(values[0]);     
        } catch (ParseException e) {     
            date = null;     
        }
        return date;
    }
 
    @SuppressWarnings("rawtypes")
    @Override    
    public String convertToString(Map context, Objecto) {
        if (o instanceof Date) {  
            return new SimpleDateFormat(format).format((Date) o);  
        }
        return StringUtils.EMPTY;   
}
 
/**
     * 更改日期格式(可以同時更新到資料庫)
     * @param format
     */
    public void changeFormat(String format) {
        this.format = format;
    }
}
           

2.全局配置檔案

建立xwork-conversion.properties,并與struts.xml放在一起。此配置檔案中定義的轉換器是全局的,也可以定義一個指定Action的轉換器。

java.util.Date=com.cdai.ssh.common.DateConverter

3.JSP頁面

<%@page
    import="com.cdai.ssh.user.vo.*"
    contentType="text/html;charset=utf-8"
%>
<%@taglib prefix="s"uri="/struts-tags"%>
 
<html>
 
    <head>
        <title>Programmer inSY</title>
    </head>
 
    <body>
   
        <s:iterator value="userList">
            <li>
                <s:property value="createdTime"/>              
            </li>
            <p>
                <s:property value="id"/>
            </p>
        </s:iterator>
   
    </body>
 
</html>
           

4.未解決問題

4.1 配置檔案位置

struts.xml和xwork-conversion.properties要放在一起,但是不放在classes根位置就會報錯。

4.2 相容Velocity

Velocity不支援Struts2的自定義轉換器。