第一步:创建项目添加依赖:
org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-starter-freemarker
第二步:修改application.yml文件:
spring:
freemarker:
charset: UTF-8 #设定Template的编码
suffix: .ftl #后缀名
template-loader-path: classpath:/templates/ #模板加载路径,多个以逗号分隔,默认: [“classpath:/templates/”]
cache: false #缓存配置,是否开启template caching
enabled: true #是否允许mvc使用freemarker
第三步:在resources/templates目录下创建模板文件index.ftl:
${title} ${msg}
第四步:创建代码静态化工具类:
@Component
public class GenUtil {
//创建Freemarker配置实例
@Resource
private Configuration configuration;
/**
* 根据模板,利用提供的数据,生成文件
*
* @param sourceFile 模板文件,带路径
* @param data 数据
* @param aimFile 最终生成的文件,若不带路径,则生成到当前项目的根目录中
*/
public void gen(String sourceFile, String aimFile, Map data) {
try {
//加载模板文件
Template template = configuration.getTemplate(sourceFile);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(aimFile), StandardCharsets.UTF_8));
template.process(data, out);
out.flush();
out.close();
} catch (IOException | TemplateException e) {
e.printStackTrace();
}
}
}
第五步:静态化测试
@SpringBootTest
public class GenTest {
@Resource
private GenUtil genUtil;
@Test
void fun(){
Map map = new HashMap();
map.put("title", "首页");
map.put("msg", "好好学习,天天向上!");
FreemarkerUtil.execute("index.ftl", "haha.html", map);
}
}
测试
运行测试代码发现在当前项目根目录下生成了一个haha.html的文件。
到此这篇关于SpringBoot整合Freemarker实现页面静态化的文章就介绍到这了,更多相关SpringBoot整合Freemarker内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!
