在项目中使用FreeMarker做为Spring MVC中的视图文件,在展示List的时候,展示的对象中带有时间字段,但是此时间字段存的是整型的毫秒值,为了更好的展示给用户,必须要进行格式化。
但是FreeMarker中,没有这样的功能方法,只是自己去实现,还好它提供了一个接口,只需要在Java代码中,实现TemplateMethodModel,则可以在FTL中使用了。下面是我实现的Java代码:
publicclassLongTimeToDateimplementsTemplateMethodModel{
/*
*(non-Javadoc)
*@seefreemarker.template.TemplateMethodModel#exec(java.util.List)
*/
@SuppressWarnings("rawtypes")
@Override
publicObjectexec(Listargs)throwsTemplateModelException{
if(null!=args&&0
SimpleDateFormatformat=newSimpleDateFormat("yyyy-MM-ddH:mm:ss");
returnformat.format(newDate(Long.parseLong((String)args.get(0))));
}else{
returnnull;
}
}
}
在方法中,将参数传进来的对象,格式化成”yyyy-MM-dd H:mm:ss”的样式返回,这样在前台界面就能看到友好样式的时间了。
为了在页面中使用,需要将它传递给页面,在网上很多文章中,都是写的放到传值的Map(一般名为root)中,但,因为我们使用的是Spring MVC,其实传递的Map就是ModelMap,所以在 Controller中,使用下面的代码将它放到ModelMap中:
@RequestMapping
publicStringbrowser(ModelMapmodel,HttpServletRequestreq,
Pluginplugin,Pagerpage){
if(log.isDebugEnabled()){
log.debug("PluginController.browser()...");
}
intcount=pluginManager.getPluginCount(plugin);
PagepageObj=processPage(page,count,model,req);
Listplugins=pluginManager.findPluginsByPage(plugin,
pageObj.getStartOfPage(),pageObj.getPageSize());
model.addAttribute("timer",newLongTimeToDate());
model.addAttribute("plugins",plugins);
returnVIEW_PREFIX+"browser";
}
上面的方法,已经能解决问题了,但还有一个问题,这样的方式,每写一个Controller,或是每个Action中要用到这个格式化方法的时候,都要向ModelMap中存值,这样就是相当相当的麻烦啦。如果做成全局的,就不需要每个都去做这样的操作了。
当然FreeMarker也提供了相应的方法,就是在配置FreeMarkerConfigurer的时候,添加freemarkerVariables,具体配置如下:
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
其中的timer,就是你在FTL文件中使用的方法名了,FTL文件不变,而Controller中也不需要置入timer了。
现在就可以像使用内置方法一样使用timer方法了。