freemarker自定义函数

本文介绍如何在Freemarker中实现自定义函数对list进行排序。通过创建实现了TemplateMethodModelEx接口的类并实现exec方法,可以在模板中调用此自定义方法完成对list的排序操作。

这里介绍freemarker的自定义函数实现对list的排序

定义自定义函数的类

创建一个普通类,并使之实现TemplateMethodModelEx接口,实现该接口的方法必须实现exec方法。在freemarker中自定义方法都需要实现该接口,并在实现exec方法。

public class MyListSort implements TemplateMethodModelEx {
    //exec方法中可以传递多个参数
    public Object exec(List list) throws TemplateModelException {
        /*get(0)获取第一个参数,即这里是要排序的list,这里需要将参数先转化为SimpleSequence,否则会报错*/
        SimpleSequence simpleSequence = (SimpleSequence) list.get(0);
        //将SimpleSequence转化为list,貌似现在这个方法过时了
        List<BigDecimal> result = simpleSequence.toList();
        //直接使用Collections.sort进行排序
        Collections.sort(result, new Comparator<BigDecimal>() {
            public int compare(BigDecimal o1, BigDecimal o2) {
    //                return o1.intValue()-o2.intValue();//降序
                return o1.intValue()-o2.intValue();//升序
            }
        });
        return result;
    }
}

在action中调用

@RequestMapping("/sortlist")
public String sottList(Model model){
    model.addAttribute("sort_int",new MyListSort());
    return "sortList";
}

页面调用

<head>
    <title>Title</title>
</head>
<body>

<!--定义变量-->
<#assign myList=[2,5,56,78,1,2,5,6,3]/>
未排序:
<#list myList as item>
    ${item}
</#list></br>
已排序
<!--调用方法-->
<#list sort_int(myList) as item>
    ${item}
</#list>
</body>
</html>

sort_int(myList):sort_init方法名,也就是model.addAttribute(“sort_int“,new MyListSort());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值