爲struts2添加freemarker的自定義方法

案例:在freemarker中直接比較兩個時間
設定當前時間(在頁面直接用${datetime("yyyy")}取得當前時間):

/**
 *類說明
 *@author ^_^
 *@version 1.0 創建時間: May 22, 2010 11:24:27 AM
 **/
public class DatetimeFreemarkerModel implements TemplateMethodModel {

	private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";   
	/**  
	 * 根據傳入的日期時間格式,在頁面上直接取得當前時間的格式化結果  
	 * 如果格式爲空或者錯誤,將返回yyyy-MM-dd HH:mm:ss  
	 * 頁面調用${datetime("yyyy")}/${datetime('yyyy')}  
	 * @see com.yourcompany.ExtendedFreemarkerManager#createConfiguration  
	 *  
	 */  
    @SuppressWarnings("unchecked")   
    public Object exec(List args) throws TemplateModelException {   
        Date date = new Date();   
        String pattern = args.get(0).toString();   
        try {   
            return new SimpleDateFormat(pattern).format(date);   
        } catch (RuntimeException e) {   
            return new SimpleDateFormat(DEFAULT_PATTERN).format(date);   
        }   
    }   


}

 然後比較兩個時間的model:

 

/**
 *類說明
 *@author ^_^
 *@version 1.0 創建時間: May 22, 2010 11:14:44 AM
 **/
 **/public class Compare2DateFreemarkerModel implements TemplateMethodModel {
	@SuppressWarnings("unchecked") 
	public Object exec(List list) throws TemplateModelException {
	        if (list == null || list.size() != 2) {
	            throw new TemplateModelException("請輸入兩個日期");
	        }
	        Object timeOne = list.get(0);
	        Object timeTwo = list.get(1);
	        Date dateOne;
	        Date dateTwo;
	        if (timeOne instanceof String) {
	            dateOne = DateUtil.getDateFromString(timeOne.toString());
	        } else {
	            dateOne = (Date) timeOne;
	        }
	        if (timeTwo instanceof String) {
	        	dateTwo = DateUtil.getDateFromString(timeTwo.toString());
	        } else {
	        	dateTwo = (Date) timeOne;
	        }
	        if(dateOne.getTime()-dateTwo.getTime()>=0){
	        	return true;
	        }else{
	        	return false;
	        } 
	 }
}

 加入模板

/**
 *類說明
 *@author ^_^
 *@version 1.0 創建時間: May 22, 2010 11:18:44 AM
 **/
public class ExtendedFreemarkerManager extends FreemarkerManager  {
	@Override
	protected Configuration createConfiguration(ServletContext servletContext)
		throws TemplateException {
		Configuration configuration = super.createConfiguration(servletContext);
		//獲得當前時間
		configuration.setSharedVariable("dateTime", new DatetimeFreemarkerModel() );
		//是否大於後者時間
		configuration.setSharedVariable("isGltDate", new Compare2DateFreemarkerModel());
		return configuration;
	}
}

 然後在struts.xml裏添加

<constant name="struts.freemarker.manager.classname"  value="com.hongwei.domi.util.ExtendedFreemarkerManager" />  

 

最後在頁面進行比較:

<#if isGltDate(dateTime("yyyy-MM-dd HH:mm"),endTime?string("yyyy-MM-dd HH:mm"))>
						<span class="red12">您計較的報告超時了</span>
						<#else>

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章