Freemarker 页面静态化技术使用入门案例

原文链接: https://www.mk2048.com/blog/blog.php?id=h0kbj0bac2ab&title=Freemarker+%E9%A1%B5%E9%9D%A2%E9%9D%99%E6%80%81%E5%8C%96%E6%8A%80%E6%9C%AF%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8%E6%A1%88%E4%BE%8B

在访问 新闻、活动、商品 详情页面时, 路径可以是 xx【id】.html, 服务器端根据请求 id, 动态生成 html 网页,下次访问数据时,无需再查询数据,直接将 html 静态页面返回。这样一来就减 少 数 据 库 交 互 , 从而提高查询性能。 
Struts2 默认使用 freemarker 实现 自定义标签模板,项目导入 struts2 就已经导入了freemarker jar 包。 
使用Freemarker步骤: 
1、 安装 freemarker eclipse 编辑插件。 
将 “freemarker_eclipseplugin” 复制 eclipse 的 dropins 文件夹 ,重启开发工具。 
2、 编辑 freemarker 的模板文件。 
通常模板文件 放在 WEB-INF 下 或者 classes 下。 
${变量} , 需要在程序中指定变量,合并到模板文件 一同输出。


hello.ftl模板文件代码:

1 <html>
2     <title>
3         ${title}
4     </title>
5     <body>
6         ${msg}
7     </body>
8 </html>

Java测试类FreemarkerTest代码:

 1 public class FreemarkerTest {
 2     @Test
 3     public void testOutput() throws IOException, TemplateException {
 4         // 配置对象, 配置模板位置
 5         Configuration configuration = new Configuration(
 6                 Configuration.VERSION_2_3_22);
 7         configuration.setDirectoryForTemplateLoading(new File(
 8                 "src/main/webapp/WEB-INF/templates"));
 9 
10         // 获取模板对象
11         Template template = configuration.getTemplate("hello.ftl");
12 
13         // 动态数据对象
14         Map<String, Object> paramterMap = new HashMap<String, Object>();
15         paramterMap.put("title", "你我他学习吧");
16         paramterMap.put("msg", "你好,这是第一个Freemarker案例!");
17 
18         // 合并输出
19         template.process(paramterMap, new PrintWriter(System.out));
20     }
21 }

更多专业前端知识,请上 【猿2048】www.mk2048.com

猜你喜欢

转载自blog.csdn.net/mabeizui9231/article/details/102773509