页面静态化之FreeMarker

freemarker 是Struts-core包中的一个依赖包,它可以实现动态页面的静态化,当某页面不经常发生改变时,使用静态化的页面可以减少对底层数据库的使用,从而减少数据库的压力.

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//通过传入的参数找静态页面
String htmlRealPath = ServletActionContext.getServletContext().getRealPath("/freemarker");

File htmlFile = new File(htmlRealPath + "/" + model.getId() + ".html");

System.out.println(htmlRealPath);
//如果不存在,就生成静态页面
if (!htmlFile.exists()) {

//freemarker配置
Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
//freemarker需要一个模板文件
configuration.setDirectoryForTemplateLoading(
new File(
ServletActionContext.getServletContext().getRealPath("/WEB-INF/freemarker_templates")));
//获得模板
Template template = configuration.getTemplate("promotion_detail.ftl");
//webService得到数据
Promotion promotion = WebClient.create(Constants.BOS_MANAGEMENT_URL + "/services/promotionService/promotion/" + model.getId())
.accept(MediaType.APPLICATION_JSON).get(Promotion.class);
//需要个Map用于向静态页面传递数据
Map<String, Object> map = new HashMap<>();
map.put("promotion", promotion);

//合并输出,并处理编码问题
//1.从map取得数据,
//2.然后使用template生成静态页面,
//3.最后通过输出流,输入为文件.
template.process(map, new OutputStreamWriter(new FileOutputStream(htmlFile), "utf-8"));

}
//解决乱码问题
ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
//复制静态页面的内容到Response中
FileUtils.copyFile(htmlFile, ServletActionContext.getResponse().getOutputStream());

模板promotion_detail.ftl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<link rel="stylesheet" type="text/css" href="css/promotion_detail.css">
<div class="container promotions" >
<div class="col-md-2 prolist">
<h5 class="title"><a href="#/promotion"><strong>返回促销列表</strong></a></h5>
<img src="images/pro.jpg" class="img-responsive">
</div>
<div class="col-md-10 procontent">
<h5 class="title">${promotion.title}</h5>
<div class="intro">
<p>活动范围: ${promotion.activeScope}</p>
<p>活动时间: ${promotion.startDate?string("yyyy-MM-dd")} -
${promotion.endDate?string("yyyy-MM-dd")}</p>
</div>
<div class="partline clearfix"></div>
<div class="promotionbox">
${promotion.description}
</div>
</div>
</div>

通过EL表达式接收数据并显示出来,还可以使用函数来解析传来的数据,例如:

1
2
${promotion.startDate?string("yyyy-MM-dd")}
${promotion.endDate?string("yyyy-MM-dd")}