- 在页面高访问量并且页面数据不会经常变化的情况下我们可以生成静态页面,下面我们来实战一波spring-boot-thymeleaf生成静态文件
- 首先引入jar包
-
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/ognl/ognl --> <dependency> <groupId>ognl</groupId> <artifactId>ognl</artifactId> <version>3.0.8</version> </dependency>
准备一份测试的模板文件到项目中index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Insert title here</title> </head> <body> <span th:text="hello + ${name}"></span> </body> </html>
-
配置相关参数
-
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.thymeleaf.TemplateEngine; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; @Configuration public class FreemarkerConfig { @Bean public TemplateEngine templateEngine() { ClassLoaderTemplateResolver classLoaderTemplateResolver = new ClassLoaderTemplateResolver(); classLoaderTemplateResolver.setPrefix("/templates/"); classLoaderTemplateResolver.setSuffix(".html"); classLoaderTemplateResolver.setCacheable(false); classLoaderTemplateResolver.setCharacterEncoding("utf-8"); TemplateEngine engine = new TemplateEngine(); engine.setTemplateResolver(classLoaderTemplateResolver); return engine; } }
增加工具类
-
package com.example.demo; import java.io.FileWriter; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; @Component public class FreemarkerUtils { @Autowired private TemplateEngine engine; /** * 生成静态文件 * @param freeTempName 模板名称 * @param context 数据内容 * @param outFilePath 输出路径 * @return */ public boolean process(String freeTempName,Context context,String outFilePath) { FileWriter fileWriter = null; try { fileWriter = new FileWriter(outFilePath); engine.process(freeTempName, context,fileWriter); } catch (IOException e) { e.printStackTrace(); return false; } finally { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); return false; } } return true; } }
注入工具类进行测试
-
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.thymeleaf.context.Context; @RestController public class IndexController { @Autowired private FreemarkerUtils freeUtrils; @RequestMapping("/") public boolean testFreemarker() throws Exception { Context context = new Context(); context.setVariable("name", "张三"); return freeUtrils.process("index", context, "D:\\workutil\\workfile\\aaa3.html"); } }
测试结果
-
转载于:https://my.oschina.net/xpx/blog/1845829