Freemarker模板应用

FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。

一、FreeMarker主要部分

FreeMarker的模板文件并不比HTML页面复杂多少,FreeMarker模板文件主要由如下4个部分组成: 
1,文本:直接输出的部分 
2,注释:<#-- ... -->格式部分,不会输出 
3,插值:即${...}或#{...}格式的部分,将使用数据模型中的部分替代输出 
4,FTL指令:FreeMarker指定,和HTML标记类似,名字前加#予以区分,不会输出 
下面是一个FreeMarker模板的例子,包含了以上所说的4个部分 

<html><br> 
<head><br> 
<title>Welcome!</title><br> 
</head><br> 
<body><br> 
<#-- 注释部分 --><br> 
<#-- 下面使用插值 --> 
<h1>Welcome ${user} !</h1><br> 
<p>We have these animals:<br> 
<u1><br> 
<#-- 使用FTL指令 --> 
<#list animals as being><br> 
   <li>${being.name} for ${being.price} Euros<br> 
<#list><br> 
<u1><br> 
</body><br> 
</html> 

二、Freemarker模板应用事例

------------------普通变量获取-------------------
${user}
---------获取Map中属性--------------
${latestProduct.url}
${latestProduct.name}
-------if判断指令-------
<#if target??>
    xxxx
<#else>
   xxxx
</#if>

<#if str == "success">
    xxx
</#if>
<#if str !== "error">
xxx
</#if>

三、自动生成代码应用

1.在lib中加入freemarker.jar的包

2.在文件templates创建一个文件 test.ftl

内容为:

   ${name},你好,${msg}

3.通过两个类完成Freemarker写入,具体看类中的使用
ResourceText.java   

public class ResourceText {
	
	//填充数据模型
	public void paddingdata(){
		String htmlTemplateNa = "test.ftl";
		Map<String,Object> variables =new HashMap<String,Object>();
	  	variables .put("name", "chenhaibin");
	  	variables .put("msg", "欢迎使用FreeMarker!");
		generateHtmlContent(htmlTemplateNa ,variables)
	}
	
	//取htmltemp所在路径	
	public String getPdfPath(){
		String path = null;
		try {
			path = ctx.getResource("classpath:templates").getFile().getPath()+File.separator;
		} catch (IOException e) {
			logger.info("取模板所在路径报错:=====get pdfTemplate path error....");
			e.printStackTrace();
		}
		logger.info("path:"+path+"####################");
		return path;
	}
	
	public String generateHtmlContent(String htmlTemplateNa, Map<String,Object> variables) throws IOException, TemplateException{     
	        BufferedWriter writer = null;   //缓冲字符输出流
	        String htmlContent = "";
	        try{
			//用Configuration实例生成Template实例,同时加载指定的模板文件
	        	Configuration config = FreemarkerConfiguration.getConfiguation(pdfUtil.getPdfPath());
	        	Template tp = config.getTemplate(htmlTemplateNa);     
	        	StringWriter stringWriter = new StringWriter();       
	        	writer = new BufferedWriter(stringWriter);  
	               //writer = new BufferedWriter(new OutputStreamWriter(System.out));
	     	
	        	tp.setEncoding("UTF-8");       
	        	tp.process(variables, writer);  
	        	htmlContent = stringWriter.toString();     
	        	writer.flush();       
	        	logger.debug("step 模板:"+htmlTemplateNa+" 生成html string 成功");
	        }finally{
	        	if(writer!=null)
	        		writer.close();     
	        }
	        return htmlContent;     
	    } 
	}

}

FreemarkerConfiguration.java

public class FreemarkerConfiguration {

	private static Configuration config = null;

	public static Configuration getConfiguation(String path) {
		if (config == null) {
			setConfiguation(path);
		}
		return config;
	}
	//创建Configuration实例,该实例负责管理FreeMarker的模板加载路径
	private static void setConfiguation(String path) {
		config = new Configuration();
		try {
			config.setDirectoryForTemplateLoading(new File(path));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
 

总结:

//Freemarker的核心代码就四句:
/1、Configuration cf = new Configuration();//实例化Configuration 
/2、cf.setDirectoryForTemplateLoading(new File(D:/myspace/freemarker/resource/template/));//为模板加载设置目录
/3、Template temp = cf.getTemplate("codeModel.ftl");//获取模板文件
/4、//设置字符串缓冲区,并写入到模板文件中
	BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	temp.process(map, bw);




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值