Freemarker 最簡略的例子法式。本站提示廣大學習愛好者:(Freemarker 最簡略的例子法式)文章只能為提供參考,不一定能成為您想要的結果。以下是Freemarker 最簡略的例子法式正文
Freemarker 最簡略的例子法式
freemarker-2.3.18.tar.gz
http://cdnetworks-kr-1.dl.sourceforge.net/project/freemarker/freemarker/2.3.18/freemarker-2.3.18.tar.gz
freemarker-2.3.13.jar:
鏈接: http://pan.百度.com/s/1eQVl9Zk 暗碼: izs5
1、經由過程String來創立模版對象,並履行插值處置
履行後,掌握台輸入成果:
import freemarker.template.Template;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
/** * Freemarker最簡略的例子 * * @author leizhimin 11-11-17 上午10:32 */
public class Test2 {
public static void main(String[] args)
throws Exception{ //創立一個模版對象
Template t = new Template(null, new StringReader("用戶名:${user};URL: ${url};姓名: ${name}"), null);
//創立插值的Map
Map map = new HashMap();
map.put("user", "lavasoft");
map.put("url", "http://www.百度.com/");
map.put("name", "百度");
//履行插值,並輸入到指定的輸入流中
t.process(map, new OutputStreamWriter(System.out)); } }
用戶名:lavasoft;URL: http://www.百度.com/; 姓名: 百度 Process finished with exit code 0
2、經由過程文件來創立模版對象,並履行插值操作
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.File;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
/** * Freemarker最簡略的例子 * * @author leizhimin 11-11-14 下晝2:44 */
public class Test { private Configuration cfg;
//模版設置裝備擺設對象 public void init() throws Exception {
//初始化FreeMarker設置裝備擺設 //創立一個Configuration實例 cfg = new Configuration();
//設置FreeMarker的模版文件夾地位
cfg.setDirectoryForTemplateLoading(new File("G:\\testprojects\\freemarkertest\\src")); }
public void process() throws Exception { //結構填湊數據的Map Map map = new HashMap();
map.put("user", "lavasoft"); map.put("url", "http://www.百度.com/");
map.put("name", "百度"); //創立模版對象 Template t = cfg.getTemplate("test.ftl");
//在模版上履行插值操作,並輸入到制訂的輸入流中 t.process(map, new OutputStreamWriter(System.out)); }
public static void main(String[] args)
throws Exception { Test hf = new Test(); hf.init(); hf.process(); } }
創立模版文件test.ftl
<html> <head> <title>Welcome!</title> </head>
<body> <h1>Welcome ${user}!</h1> <p>Our latest product: <a href="${url}">${name}</a>! </body>
</html> 尊重的用戶你好: 用戶名:${user}; URL: ${url}; 姓名: ${name}
履行後,掌握台輸入成果以下:
<html> <head> <title>Welcome!</title> </head> <body> <h1>Welcome lavasoft!</h1> <p>Our latest product: <a href="http://www.百度.com/">百度</a>! </body> </html> 尊重的用戶你好: 用戶名:lavasoft; URL: http://www.百度.com/; 姓名: 百度 Process finished with exit code 0