在FTL文件中使用自定義的Java方法

在項目中使用FreeMarker作爲Spring MVC中的視圖文件,在展現List的時候,展現的對象中帶有時間字段,可是此時間字段存的是整型的毫秒值,爲了更好的展現給用戶,必需要進行格式化。java

可是FreeMarker中,沒有這樣的功能方法,只是本身去實現,還好它提供了一個接口,只須要在Java代碼中,實現TemplateMethodModel,則能夠在FTL中使用了。下面是我實現的Java代碼:web

public class LongTimeToDate implements TemplateMethodModel {

	/*
	 * (non-Javadoc)
	 * @see freemarker.template.TemplateMethodModel#exec(java.util.List)
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public Object exec(List args) throws TemplateModelException {
		if (null != args && 0 < args.size()) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd H:mm:ss");
			return format.format(new Date(Long.parseLong((String) args.get(0))));
		} else {
			return null;
		}
	}

}

在方法中,將參數傳進來的對象,格式化成」yyyy-MM-dd H:mm:ss」的樣式返回,這樣在前臺界面就能看到友好樣式的時間了。spring

爲了在頁面中使用,須要將它傳遞給頁面,在網上不少文章中,都是寫的放到傳值的Map(通常名爲root)中,但,由於咱們使用的是Spring MVC,其實傳遞的Map就是ModelMap,因此在 Controller中,使用下面的代碼將它放到ModelMap中:app

@RequestMapping
	public String browser(ModelMap model, HttpServletRequest req,
			Plugin plugin, Pager page) {
		if (log.isDebugEnabled()) {
			log.debug("PluginController.browser()...");
		}
		int count = pluginManager.getPluginCount(plugin);

		Page pageObj = processPage(page, count, model, req);

		List<Plugin> plugins = pluginManager.findPluginsByPage(plugin,
				pageObj.getStartOfPage(), pageObj.getPageSize());

		model.addAttribute("timer", new LongTimeToDate());
		model.addAttribute("plugins", plugins);
		return VIEW_PREFIX + "browser";
	}

上面的方法,已經能解決問題了,但還有一個問題,這樣的方式,每寫一個Controller,或是每一個Action中要用到這個格式化方法的時候,都要向ModelMap中存值,這樣就是至關至關的麻煩啦。若是作成全局的,就不須要每一個都去作這樣的操做了。ide

固然FreeMarker也提供了相應的方法,就是在配置FreeMarkerConfigurer的時候,添加freemarkerVariables,具體配置以下:spa

<bean id="freemarkerConfig"
	class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
	<property name="templateLoaderPath" value="/WEB-INF/pages/" />
	<property name="defaultEncoding" value="UTF-8" />
	<property name="freemarkerVariables">
		<map>
			<entry key="webroot" value="/nap" />
			<entry key="timer" value-ref="longTimeToDate" />
		</map>
	</property>
</bean>
<bean id="longTimeToDate" class="com.xxx.nap.util.freemarker.LongTimeToDate" />

其中的timer,就是你在FTL文件中使用的方法名了,FTL文件不變,而Controller中也不須要置入timer了。debug

如今就能夠像使用內置方法同樣使用timer方法了。code

相關文章
相關標籤/搜索