这里介绍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());