1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > SpringBoot整合Freemarker实现页面静态化

SpringBoot整合Freemarker实现页面静态化

时间:2021-04-27 03:40:41

相关推荐

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 cachingenabled: true #是否允许mvc使用freemarker

第三步:在resources/templates目录下创建模板文件index.ftl:

<html><head><title>${title}</title></head><body><h2>${msg}</h2></body></html>

第四步:创建代码静态化工具类:

@Componentpublic class GenUtil {//创建Freemarker配置实例@Resourceprivate 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();}}}

第五步:静态化测试

@SpringBootTestpublic class GenTest {@Resourceprivate GenUtil genUtil;@Testvoid fun(){Map<String, Object> map = new HashMap<>();map.put("title", "首页");map.put("msg", "好好学习,天天向上!");FreemarkerUtil.execute("index.ftl", "haha.html", map);}}

测试

运行测试代码发现在当前项目根目录下生成了一个haha.html的文件。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。