页面静态化
FreeMarker
中文参考文档
是一个java语言开发的模板引擎
场景:
- 页面静态化生成(把一个动态加载数据的页面生成html的过程,叫静态化)
- 合同模板生成
- 邮件模板生成
- 自动生成代码
原理/组成:
- Template:模板
- Model:模板要用到的数据
- Output:模板+数据渲染后生成的静态html
ftl四种元素
文本 非以下三项均视为文本
指令 <#include />
插值Interpolation ${}
注释 <#-- -->
演示代码
public class FreeMarkerTest {
public static void main(String[] args) throws Exception {
//创建freemarker的配置对象
Configuration configuration = new Configuration(Configuration.getVersion());
//设置模板文件所在目录
configuration.setDirectoryForTemplateLoading(new File("E:/testftl"));
//设置字符集
configuration.setDefaultEncoding("utf-8");
//加载模板文件
Template template = configuration.getTemplate("test.ftl");
//准备模板文件中所需要的数据,通常是通过Map进行构造
Map map = new HashMap();
//普通字符串 ${entity}
map.put("entity", "CheckGroup");
//实体类对象 ${checkItem.id}
CheckItem checkItem = new CheckItem();
checkItem.setId(22);
checkItem.setName("jack");
map.put("checkItem", checkItem);
//准备输出流对象,用于输出静态文件
Writer writer = new FileWriter("E:/testftl/CheckGroup.java");
//输出
template.process(map, writer);
//关闭流
writer.close();
}
}
spring集成freemarker
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<!--指定模板文件所在目录-->
<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
<!--指定字符集-->
<property name="defaultEncoding" value="UTF-8" />
</bean>
常用指令
<#include path options>
options 例如encoding=utf-8之类的设置
引入其他页面, 解耦
<#assign param=value>
参数定义, 会覆盖同名的外部传入的数据, 常用于开发调试
<#list sequence>
Part executed once if we have more than 0 items
<#items as item>
Part repeated for each item
</#items>
Part executed once if we have more than 0 items
<#else>
Part executed when there are 0 items
</#list>
<#if >
<#else>
</#if>
内置函数
//参见官方文档
Last updated date: ${lastUpdated?string('yyyy-MM-dd')}<br>
Last updated date: ${lastUpdated?date}<br>
Last updated time: ${lastUpdated?time}<br>
Last updated time: ${lastUpdated?datetime}<br>
Freemarker使用小结
1.什么是网页静态化技术
随着用户访问量以及数据量的增大,网页静态化技术方案如今越来越流行。
什么是网页静态化技术呢?简单来说就是将网页以纯静态方式的形式展现。
2.网页静态化技术与缓存技术的比较
共同点:都可以减小数据库的访问压力。
区别:
(1)缓存技术适用于小规模的数据。以及一些经常变动的数据。
(2)网页静态化技术适用于大规模但是变化不太频繁的数据。
3.网页静态化技术的应用场景
(1)新闻门户网站的文章类型频道一般都用到了网页静态化技术。点击新闻直接会跳到静态化的页面。
(2)电商网站的商品详情页也十分常用,我们在存储商品的时候会生成静态化页面,点击商品详情,会直接跳到生成的商品详情的静态化页面。
(3)网页静态化技术可以结合Nginx这种高性能web服务器来提高并发访问量。
4.什么是FreeMarker
FreeMarker是一款用Java语言编写的模板引擎,用它可以通过模板和要改变的数据来生成输出文本(例如HTML网页,配置文件,源代码等),作为用来实现网页静态化技术的一种手段。FreeMarker的使用率大大超过其他一些技术。对于系统中频繁使用数据库进行查询但是内容更新很小的应用,都可以用FreeMarker将网页静态化,这样就避免了大量的数据库访问请求,从而提高网站的性能。
Thymeleaf
开箱即用
任何可以建模为DOM树(无论是否为XML)的东西都可以被Thymeleaf有效地作为模板处理。(邮件模板, 静态页面, 合同模板, 代码自动生成)
基本语法
- $ 引用变量
- @ URI
- # 内置工具类
th:text
th:utext # 解析html
th:src
th:href
# 类似于<form>表单的action属性
<form th:action="@{/test/hello}" >
<input th:type="text" th:name="id">
<button>提交</button>
</form>
# 遍历类似于jstl的<c:foreach>
<tr th:each="user,userStat:${users}">
<td>下标:<span th:text="${userStat.index}"></span>,</td>
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.address}"></td>
</tr>
<div th:each="map,mapStat:${dataMap}">
<div th:text="${map}"></div>
key:<span th:text="${mapStat.current.key}"></span><br/>
value:<span th:text="${mapStat.current.value}"></span><br/>
</div>
<div th:each="name,nameStat:${names}">
<span th:text="${nameStat.count}"></span><span th:text="${name}"></span>
</div>
# 日期
<div>
<span th:text="${#dates.format(now,'yyyy-MM-dd hh:ss:mm')}"></span>
</div>
th:if="${#maps.containsKey(searchMap,'brand')}
th:fragment
th:include
th:classappend
th:inline='javascript'
springboot集成thymeleaf
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
application.yml
# 关闭缓存
spring:
thymeleaf:
cache: false
示例代码
@Override
public void generateStaticPage(String spuId) throws Exception{
// 获取Context对象
Context context = new Context();
// 获取页面需要的数据
Map itemData = getItemData(spuId);
context.setVariables(itemData);
//
File dir = new File(pagePath);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir + "/" + spuId + ".html");
Writer writer = null;
try {
writer = new PrintWriter(file);
templateEngine.process("item", context, writer);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("生成静态页面出错");
} finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}