java代码如下:
class="java" name="code">import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveModel;
/**
* FreeMarker自定义宏
* 获取App下载排行列表
* 参数包括 length(列表长度) mtypeCode(主类型代码) typeCode(小类型代码) rankMode(排行模式1、2、3)
* @author shannon
*
*/
public class FMAppRankDirective implements TemplateDirectiveModel {
@Resource(name = "appRankService")
private AppRankService appRankService;
@SuppressWarnings("unchecked")
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException {
//DirectiveUtils是借用jeecms项目中的工具类,主要是因为它集成了一些异常处理功能,
//其实完全可以不用它,params是个Map,自己通过key取值就可以了,做一下空值判断
Integer length = DirectiveUtils.getInt("length", params);
Integer mtypeCode = DirectiveUtils.getInt("mtypeCode", params);
Integer typeCode = DirectiveUtils.getInt("typeCode", params);
Integer rankMode = DirectiveUtils.getInt("rankMode", params);
ArrayList<App> rankList = appRankService.getRankList(length, mtypeCode, typeCode, rankMode);
env.setVariable("appRankList", ObjectWrapper.DEFAULT_WRAPPER.wrap(rankList));
if (body != null) {
body.render(env.getOut());
}
}
}
页面引用有多种方法:
一:
<bean id="fp" class="xxxx.tag.FMAppRankDirective"></bean>
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
此处省略
<property name="freemarkerVariables">
<map>
<entry key="fp" value-ref="fp"/>
</map>
</property>
</bean>
然后页面直接用 <@fp 的方式调用,
二:在页面上直接导入,如:
<#assign fp= "xxxx.tag.FMAppRankDirective"?new()>
推荐用第一种