spring boot 整合Freemarker

本文详细介绍了如何在Spring Boot项目中整合Freemarker,包括添加依赖、配置属性、注册Bean、编写FTL文件以及进行测试。通过这些步骤,可以将模板引擎成功集成并用于渲染输出。作者指出,此实践可将结果输出到控制台,也可扩展到文件或返回字符串,欢迎对Spring初学者的探讨和指正。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

添加依赖


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

配置属性文件


spring.freemarker.suffix=.ftl
spring.freemarker.templateEncoding=UTF-8
spring.freemarker.templateLoaderPath=classpath:/templates/

注册Bean


@org.springframework.context.annotation.Configuration
public class FreeMarkerConfig {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Bean
    public Configuration getFreeMarkerConfiguration(){
        return freeMarkerConfigurer.getConfiguration();
    }

    public void resolveMap(Map<String,String> model, String templateName){
        try {
            Template template = this.getFreeMarkerConfiguration().getTemplate(templateName);
            template.process(model, new OutputStreamWriter(System.out));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}

编写ftl文件


hello world
${name}
${age}
this is test

测试


@Autowired
FreeMarkerConfig fc;
@Test
public void FreeMarkerConfigTest(){
    Map<String,String> result = new HashMap<>();
    result.put("name","test");
    result.put("age","20");
    fc.resolveMap(result,"index.ftl");
}

附言


这个只是将模板引擎加载进来,将渲染后的结果输出到控制台,也可以采用别的办法输出到文件或者返回一个string。本人刚开始学spring,哪里有错误的地方,欢迎指正交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值