这篇文章主要介绍了SpringBoot整合Freemarker实现页面静态化,第一步要创建项目添加依赖,本文分步骤给大家详细讲解,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
第一步:创建项目添加依赖:
<!--web和actuator(图形监控用)基本上都是一起出现的-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
第二步:修改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:
<html>
<head>
<title>${title}</title>
</head>
<body>
<h2>${msg}</h2>
</body>
</html>
第四步:创建代码静态化工具类:
@Component
public class GenUtil {
//创建Freemarker配置实例
@Resource
private Configuration configuration;
/**
* 根据模板,利用提供的数据,生成文件
*
* @param sourceFile 模板文件,带路径
* @param data 数据
* @param aimFile 最终生成的文件,若不带路径,则生成到当前项目的根目录中
*/
public void gen(String sourceFile, String aimFile, Map<String, Object> 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<String, Object> map = new HashMap<>();
map.put("title", "首页");
map.put("msg", "好好学习,天天向上!");
FreemarkerUtil.execute("index.ftl", "haha.html", map);
}
}
测试
运行测试代码发现在当前项目根目录下生成了一个haha.html的文件。
到此这篇关于SpringBoot整合Freemarker实现页面静态化的文章就介绍到这了,更多相关SpringBoot整合Freemarker内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:SpringBoot整合Freemarker实现页面静态化的详细步骤
猜你喜欢
- 深入了解Spring的事务传播机制 2023-06-02
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- Java中的日期时间处理及格式化处理 2023-04-18
- JSP 制作验证码的实例详解 2023-07-30
- Java实现顺序表的操作详解 2023-05-19
- JSP页面间传值问题实例简析 2023-08-03
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- Spring Security权限想要细化到按钮实现示例 2023-03-07