实现动态页面静态化 本文章使用freeMarker的方法将页面静态化。下面介绍下最基础的使用方式。
需要三个步骤。
maven直接添加下面的dependency即可。
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
public JsonResult test(HttpSession session)
{
JsonResult jsonResult = new JsonResult();
String webappPath = session.getServletContext().getRealPath("/");
// 配置对象, 配置模板位置
Configuration configuration = new Configuration(
Configuration.VERSION_2_3_22);
try {
configuration.setDirectoryForTemplateLoading(new File(
webappPath+"\\WEB-INF\\template"));
} catch (IOException e) {
e.printStackTrace();
}
// 获取模板对象
Template template = null;
try {
template = configuration.getTemplate("test.ftl");
} catch (IOException e) {
e.printStackTrace();
}
// 动态数据对象
Map<String, Object> paramterMap = new HashMap<String, Object>();
paramterMap.put("title", "hello world");
paramterMap.put("msg", "这是一个Freemarker!");
// 合并输出,new PrintWriter()中的参数为生成静态HTML的地址。
try {
template.process(paramterMap, new PrintWriter(webappPath+"\\assets\\test.html"));
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResult;
}
在WEB-INF文件夹中创建模板,
内容为:(取值方式和jstl很相似)
<html>
<title>
${title}
</title>
<body>
${msg}
</body>
</html>
运行controller即可生成HTML文件。如下
{{ cmt.username }}
{{ cmt.content }}
{{ cmt.commentDate | formatDate('YYYY.MM.DD hh:mm') }}