原理
静态化是指把动态生成的HTML页面变为静态内容保存,以后用户的请求到来,直接访问静态页面,不再经过服务的渲染。静态的HTML页面可以部署在nginx中,从而大大提高并发能力,减小tomcat压力。
工具类import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Map;
@Component
public class ThymeleafUtil {
@Resource
private TemplateEngine templateEngine;
/**
* 生成静态页面
*
* @param templateName 放在根路径templates下的的模板文件的名称
* @param dest 带路径的目标文件
* @param data 数据
* @param key 模板中的key
* @return 成功返回true,失败返回false
*/
public boolean genPage(String templateName, String dest, Object data, String key) {
// 创建上下文,
Context context = new Context();
// 把数据加入上下文
context.setVariables(Map.of(key, data));
// 创建输出流,关联到一个临时文件
File destFile = new File(dest);
// 备份原页面文件
try (PrintWriter writer = new PrintWriter(destFile, "UTF-8")) {
// 利用thymeleaf模板引擎生成 静态页面
templateEngine.process(templateName, context, writer);
return true;
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
return false;
}
}
}
代码解释:
- Context :上下文,用来保存模型数据,当模板引擎渲染时,可以从Context上下文中获取数据用于渲染。在SpringBoot中使用时,Model中的数据就会被处理到Context中,作为模板渲染的数据使用。
- TemplateResolver:模板解析器,用来读取模板相关的配置,例如:模板存放的位置信息,模板文件名称,模板文件的类型等等。在SpringBoot中使用时,TemplateResolver已经由其创建完成,并且各种配置也都有默认值,比如模板存放位置,其默认值就是:templates。比如模板文件类型,其默认值就是html。
- TemplateEngine:模板引擎,用来解析模板的引擎,需要使用到上下文、模板解析器。分别从两者中获取模板中需要的数据,模板文件。然后利用内置的语法规则解析,从而输出解析后的文件。
- templateEngine.process(“模板名”, context, writer)有三个参数,分别为:
- 模板名称 上下文:
- 里面包含模型数据 writer:
- 输出目的地的流
在输出时,我们可以指定输出的目的地,如果目的地是Response的流,那就是网络响应。如果目的地是本地文件,那就实现静态化了。
测试- 1.在src/templates目录下创建一个thymeleaf页面模板,比如模板
deptList.html
代码如下::
Hello Thymeleaf
访问列表
部门编号
部门名称
部门地址
- 2.测试生成页面
@SpringBootTest
public class PageStaticDemo {
@Resource
private ThymeleafUtil thymeleafUtil;
@Test
public void fun() throws Exception {
List depts = new ArrayList();
depts.add(new Dept(10, "ACCOUNTING", "NEWYORK"));
depts.add(new Dept(20, "RESEARCH", "DALLAS"));
depts.add(new Dept(30, "SALES", "CHICAGO"));
depts.add(new Dept(40, "OPERATIONS", "BOSTON"));
boolean res = thymeleafUtil.genPage("deptList", "asdf1234.html", depts, "depts");
System.out.println(res ? "ok" : "error");
}
}
结果
最终生成的页面代码如下:
Hello Thymeleaf
访问列表
部门编号
部门名称
部门地址
10
ACCOUNTING
NEWYORK
20
RESEARCH
DALLAS
30
SALES
CHICAGO
40
OPERATIONS
BOSTON