springboot整合freemarker生成静态xml

Freemarker模板引擎实战
本文介绍如何在Spring Boot项目中使用Freemarker模板引擎,包括配置依赖、设置模板路径和编码方式等步骤,并通过一个具体示例展示了如何将数据传递给模板并生成HTML文件。

1. pom 文件 

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

2. 接下来是freemarker的一些基本设置,包括他的ftl文件路径,也就是他的模板路径,我在resources下templates下,后边是application.properties中的设置:

spring.freemarker.suffix=.ftl
spring.freemarker.templateEncoding=UTF-8
spring.freemarker.templateLoaderPath=classpath:/templates/
spring.freemarker.content-type=text/html

例如,我们添加一个模板文件,叫做 welcome.ftl。

<!DOCTYPE html>
<html lang="en">
<body>
    Date: ${time?date}<br>
    Message: ${message}
</body>
</html>
@RestController("template.freemarkerController2")
@EnableAutoConfiguration
public class Welcome2Controller {
@Autowired
private Configuration configuration;
@RequestMapping("/template/freemarker/welcome2")
public String welcome2(Map model) throws Exception {
model.put("time", new Date());
model.put("message", "梁桂钊");

Template template = configuration.getTemplate("welcome.ftl");
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

FileUtils.writeStringToFile(new File("d:/welcome.html"), content);

return "welcome";
}
}

 我这次做的是xml 的模板,开始怎么都不好使。后来去掉xml 头部<?xml 这行就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值