在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

相关文章
相关标签/搜索