從零學習freemarker(2)給模板傳遞引數的測試
阿新 • • 發佈:2019-01-22
原文:http://www.java2000.net/p7841
程式程式碼
模板
執行結果
分析:
資料結構為
(root)
|
+- user = "java2000.net"
|
+- latestProduct
|
+- url = "http://www.java2000.net"
|
+- name = "Java世紀網"
我們使用巢狀的Map給其傳遞引數
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
程式程式碼
- package freemarker;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.OutputStreamWriter;
- import java.io.Writer;
- import java.util.HashMap;
- import java.util.Map;
- import freemarker.template.Configuration;
- import freemarker.template.Template;
- publicclass Test2 {
- private Configuration cfg;
- public Configuration getCfg() {
- return cfg;
- }
- publicvoid init() throws Exception {
- cfg = new Configuration();
- cfg.setDirectoryForTemplateLoading(new File("bin/freemaker"));
- }
- publicstaticvoid main(String[] args) throws Exception {
- Test2 obj = new Test2();
- obj.init();
- Map root = new HashMap();
- root.put("user", "java2000.net");
- Map latestProduct = new HashMap();
- latestProduct.put("url", "http://www.java2000.net");
- latestProduct.put("name", "Java世紀網");
- root.put("latestProduct", latestProduct);
- Template t = obj.getCfg().getTemplate("Test2.ftl");
- Writer out =
- t.process(root, out);
- System.out.println("Successfull................");
- }
- }
模板
- <html>
- <head>
- <title>Welcome!</title>
- </head>
- <body>
- <h1>Welcome ${user}!</h1>
- <p>Our latest product:
- <ahref="${latestProduct.url}">${latestProduct.name}</a>!
- </body>
- </html>
執行結果
- <html>
- <head>
- <title>Welcome!</title>
- </head>
- <body>
- <h1>Welcome java2000.net!</h1>
- <p>Our latest product:
- <ahref="http://www.java2000.net">Java世紀網</a>!
- </body>
- </html>
分析:
資料結構為
(root)
|
+- user = "java2000.net"
|
+- latestProduct
|
+- url = "http://www.java2000.net"
|
+- name = "Java世紀網"
我們使用巢狀的Map給其傳遞引數
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>