当前位置: 移动技术网 > IT编程>开发语言>Java > Freemarker 最简单的例子程序

Freemarker 最简单的例子程序

2019年07月22日  | 移动技术网IT编程  | 我要评论
freemarker 最简单的例子程序   freemarker-2.3.18.tar.gz http://cdnetworks-kr-1.dl.sourc

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.baidu.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.baidu.com/");  
 map.put("name", "百度");  
 //执行插值,并输出到指定的输出流中  
 t.process(map, new outputstreamwriter(system.out));  } }

用户名:lavasoft;url:    http://www.baidu.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.baidu.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.baidu.com/">百度</a>! </body> </html> 
尊敬的用户你好: 用户名:lavasoft; url: http://www.baidu.com/; 姓名:  百度 process finished with exit code 0


如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网