freemarker模板引擎使用的高级技巧

字符串、集合操作

<#assign a = 'hello'/>
<#assign b = 'world'/>

 

1. 字符串连接

${a + b}

2. 字符串截取

${(a + b)?substring(5,8)}

3.字符串长度 

${(a + b)?length}

4.字符串大小写 


${(a + b)?upper_case}

${(a + b)?lower_case}

5. 字符串首次出现的位置

${(a + b)?index_of('w')

 6.字符串替换

${(a + b)?replace('w','A')}

 

自定义函数

1. 自定义函数实现数组排序

声明数组并显示未排序之前的数组

<#assign myList = [2,3,4,5,1,8,9,8,7]/>
        
  • 未排序
  • <#list myList as item> ${item}

    编写自定义函数类

    public class SortMethod implements TemplateMethodModelEx {
        @Override
        public Object exec(List arguments) throws TemplateModelException {
    
            //获取第一个参数
            SimpleSequence arg0 = (SimpleSequence)arguments.get(0);
            List list = arg0.toList();
    
            Collections.sort(list, new Comparator() {
                @Override
                public int compare(BigDecimal o1, BigDecimal o2) {
                    return o1.intValue() - o2.intValue(); //升序
                   // return o1.intValue() - o2.intValue(); //降序
                }
            });
            return list;
        }
    }
    

    通过controller层传入到前端页面 

    mv.addObject("sort_int",new SortMethod());

    实现数组排序 

     
  • 升序、降序排列
  • <#list sort_int(myList) as item> ${item}

    2. 内建函数实现数组排序

      <#assign myList = [2,3,4,5,1,8,9,8,7]/>
            
  • 内建函数实现数组排序
  • <#list myList?sort as item> ${item_index} : ${item}

     

     

     

     

     

     

     

    你可能感兴趣的:(java)