`
shenkun_918
  • 浏览: 26653 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

项目中用到的freemarker

阅读更多

freemarker的中文乱码问题,在项目过程总是遇到,记录下来,方便以后运用。项目中两处用到freemarker,一是邮件发送静态页面。二是做统计时,要用flash的饼图和柱状图显示,在网上找到一个,只需要让配置的xml动态变化,用freemarker动态生成其配置文件。首先,freemarker是支持国际化的,模板的文件名如:bargain_zh_CN.ftl,要加上_zh_CN。把写的程序贴上来方便查。

public class TemplateConfiguration {
	
	/**
	 * 传入装有信息的root,模板文件所在的路径pah和模板文件名fileName
     * 返回的是经过map信息改变后的摸板内容
	 */
	 public static String getEmailContext(Map root,String path,String fileName) throws Exception{
			Configuration cfg = new Configuration();
			cfg.setEncoding(Locale.getDefault(), "UTF-8");
			cfg.setDirectoryForTemplateLoading(new File(path));
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20,250));
			
			Template temp = cfg.getTemplate(fileName);
			temp.setEncoding("UTF-8");
			java.io.StringWriter stringWriter = new StringWriter();
			Writer out = new BufferedWriter(stringWriter);
			temp.process(root, out);
			out.flush();
			//System.out.println(stringWriter.toString());
			return stringWriter.toString();
	}
	 
	 /*
	  * 获取信息生成flash配置文件的xml
      *root 中为要要写入模板中的信息,path为模板所在路径,fileName为模板文件名
      *outFile为生成文件的路径和文件名(*.xml,*.html,.......) 
	  */
	 public static void getTemplateContext(Map root,String path,String fileName,String outFile) throws Exception{
			Configuration cfg = new Configuration();
			cfg.setEncoding(Locale.getDefault(), "UTF-8");
			cfg.setDirectoryForTemplateLoading(new File(path));
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20,250));
			
			Template temp = cfg.getTemplate(fileName);
			temp.setEncoding("UTF-8");
			Writer writerFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
			temp.process(root,writerFile);
			writerFile.flush();
	}
	 
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics