Freemarker模板

@SpringBootTest
public class FreemakerTest {
    @Autowired
    FreemarkerComponent freemarkerComponent;

    @Test
    public void freemakerTest() throws Exception {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("Mike","123","女"));
        studentList.add(new Student("Bill","456","男"));

        String content = freemarkerComponent.getContent("hello", studentList);
        System.out.println(content);
    }
}

2.模板配置组件

@Component
@Slf4j
public class FreemarkerComponent {

    @Value("${spring.freemarker.suffix}")
    private String suffix;

    @Autowired
    private Configuration configuration;

    /**
     * <p> 
     *  拼接模板内容
     * </p>
     * @param temlateName  模板名称
     * @param dataModel 数据模型
     */
    public String getContent(String temlateName, Object dataModel) {
        try {
            temlateName += suffix;
            Template template = configuration.getTemplate(temlateName);
            StringWriter writer = new StringWriter();
            Map<String, Object> map = new HashMap();
            map.put("data", dataModel);
            template.process(map, writer);
            return writer.toString();
        } catch (Exception e) {
            log.error("根据模板[" + temlateName + "]得到结果时异常", e);
            throw BizException.create(ResultCodeEnum.TEMPLATE_ERROR);
        }
    }

}

3.模板文件

[
<#list data as item>
    {
    "userName":"${item.username}",
    "passWord":"${item.password}"
    }
    <#if item_has_next>
    ,
    </#if>
</#list>
]

4.application.yml 中的freemaker配置

spring:
  # 模板配置
  freemarker:
    charset: UTF-8
    settings:
      # 设置为兼容模式。当变量为null或者变量不存在时都不会抛出异常。
      classic_compatible: true
      # 数字格式化,格式化为6位小数
      number_format: 0.######
    # 模板存放地址,即/resources 后面的地址 
    template-loader-path: classpath:/ftl/
    # 指定Freemarker模板文件的后缀名
    suffix: .ftl
      # 关闭模板缓存,方便测试
    cache: false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值