FreeMarker工具类,用来根据模板文件生成html文件,html字符串等

----使用FreeMarker来生成

1、静态Htm文件

2、Html字符串

3、html的response响应流

4、控制台输出流

package com.XX.XX.freemarker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.cache.WebappTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Freemarker {
	  private HttpServletRequest request;
	  private HttpServletResponse response;
	  private ServletContext context;
	  
	  private String ftlName;//模板名称
	  
	  private String generatedFilePath;//待生成的静态文件存放的位置(默认“/site/generated”)
	  
	  private String generatedFileName;//待生成的静态文件名称
	  
	  private Map map;//Freemarker数据模型
	  
	  private String templatePath;//模板存放的位置(默认“/WEB-INF/templates”)
	  
	  private String encoding;//编码格式(默认“gbk”)
	  
	  private String articleTemplatePath;//文章模板存放的位置,动态设置
	  
	  public String getArticleTemplatePath() {
		return articleTemplatePath;
	}

	public void setArticleTemplatePath(String articleTemplatePath) {
		this.articleTemplatePath = articleTemplatePath;
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public String getFtlName() {
		return ftlName;
	}

	public void setFtlName(String ftlName) {
		this.ftlName = ftlName;
	}

	public String getGeneratedFileName() {
		return generatedFileName;
	}

	public void setGeneratedFileName(String generatedFileName) {
		this.generatedFileName = generatedFileName;
	}

	public String getGeneratedFilePath() {
		return generatedFilePath;
	}

	public void setGeneratedFilePath(String generatedFilePath) {
		this.generatedFilePath = generatedFilePath;
	}

	public Map getMap() {
		return map;
	}

	public void setMap(Map map) {
		this.map = map;
	}

	public String getTemplatePath() {
		return templatePath;
	}

	public void setTemplatePath(String templatePath) {
		this.templatePath = templatePath;
	}

	public Freemarker()
	  {
	  }

	  public Freemarker(ServletContext context)
	  {
	    this.context = context;
	  }

	  public void init(HttpServletRequest request, HttpServletResponse response) {
	    this.request = request;
	    this.response = response;
	  }

	  public void init(HttpServletRequest request, HttpServletResponse response, ServletContext context)
	  {
	    this.request = request;
	    this.response = response;
	    this.context = context;
	  }

	  /**
	   * 
	   * @param ftl 模板名称,包括后缀名----必传
	   * @param htmlPath 待生成的HTML存在服务器的位置
	   * @param htmlFileName 待生成的HTML文件名----必传
	   * @param map 模板数据----必传
	   * @param templatePath 模板存放在位置
	   * @param encode 编码格式
	   * @return string 生成的HTML文件的相对路径 不带contextPath
	   * @throws IOException
	   * @throws TemplateException
	   */
	  public String process(String ftl,String htmlPath,String htmlFileName, Map map, String templatePath, String encode)
	  {
	    BufferedWriter buff = null;
		Writer out = null;
		String generatedFile = "";
		try 
		{
			Configuration freemarkerCfg = new Configuration();
			//生成的HTML文件存放的位置
			if (StringUtils.isBlank(htmlPath))
			{
				htmlPath = this.request.getContextPath() + "/generated";
			}
			else if (!htmlPath.startsWith("/"))
			{
				htmlPath = "/" + htmlPath;
			}
			if (StringUtils.isBlank(templatePath))
			{
				templatePath = this.request.getContextPath() + "/templates/default";
			}
			else if (!templatePath.startsWith("/"))
			{
				templatePath = "/" + templatePath;
			}
			if (StringUtils.isBlank(encode))
			{
				encode = "UTF-8";
			}
			if (-1 == ftlName.lastIndexOf('.'))
			{
				ftlName = ftlName + ".ftl";
			}
			if (-1 == generatedFileName.lastIndexOf('.'))
			{
				generatedFileName = generatedFileName + ".html";
			}
			//加载模板所在路径
			WebappTemplateLoader loader1 = new WebappTemplateLoader(this.context, templatePath); 
			WebappTemplateLoader loader2 = null;
			if (StringUtils.isNotBlank(articleTemplatePath))
			{
				loader2 = new WebappTemplateLoader(this.context, articleTemplatePath);
			}
			else
			{
				loader2 = new WebappTemplateLoader(this.context, "/dj/sharedtemplates/");
			}
			MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(new TemplateLoader[] {loader1,loader2});
			freemarkerCfg.setTemplateLoader(multiTemplateLoader);
	        Properties p = new Properties();   
	        try {
				p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("freemarker.properties"));   
				freemarkerCfg.setSettings(p);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (TemplateException e) {
				e.printStackTrace();
			}  


			Template template = freemarkerCfg.getTemplate(ftl);
			template.setEncoding(encode);
			this.request.setCharacterEncoding(encode);
			this.response.setContentType("text/html; charset=" + encode);
			String path = this.context.getRealPath("/" + htmlPath);
			File dir = new File(path);
			if (!dir.exists())
			{
				dir.mkdirs();
			}
			buff = new BufferedWriter(new FileWriter(path + htmlFileName));
			File htmlFile = new File(path + File.separator + htmlFileName);
			out = new BufferedWriter(new OutputStreamWriter(
			  new FileOutputStream(htmlFile), encode));
			template.process(map, out);
			generatedFile = htmlPath + "/" + htmlFileName;
		} 
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} 
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		} 
		catch (TemplateException e)
		{
			e.printStackTrace();
		}
		finally
		{
		    try 
		    {
		    	if (null != buff)
		    	{
		    		buff.close();
		    	}
		    	if (null != out)
		    	{
					out.flush();
					out.close();
		    	}
			} 
		    catch (IOException e)
		    {
				e.printStackTrace();
			}
		}
	    return generatedFile;
	  }
	  
	  /**
	   * 处理模板文件并生成静态文件
	   * @return 生成文件的路径
	   */
	  public String process()
	  {
	    BufferedWriter buff = null;
		Writer out = null;
		String generatedFile = "";
		try 
		{
			Configuration freemarkerCfg = new Configuration();
			//生成的HTML文件存放的位置
			if (StringUtils.isBlank(generatedFilePath))
			{
				generatedFilePath = this.request.getContextPath() + "/generated/";
			}
			else if (!generatedFilePath.startsWith("/"))
			{
				generatedFilePath = "/" + generatedFilePath;
			}
			if (StringUtils.isBlank(templatePath))
			{
				templatePath = this.request.getContextPath() + "/templates/default";
			}
			else if (!templatePath.startsWith("/"))
			{
				templatePath = "/" + templatePath;
			}
			if (StringUtils.isBlank(encoding))
			{
				encoding = "GBK";
			}
			if (-1 == ftlName.lastIndexOf('.'))
			{
				ftlName = ftlName + ".ftl";
			}
			if (-1 == generatedFileName.lastIndexOf('.'))
			{
				generatedFileName = generatedFileName + ".html";
			}
			//加载模板所在路径(使用多模板加载器加载模板文件)
			WebappTemplateLoader loader1 = new WebappTemplateLoader(this.context, templatePath); 
			WebappTemplateLoader loader2 = null;
			if (StringUtils.isNotBlank(articleTemplatePath))
			{
				loader2 = new WebappTemplateLoader(this.context, articleTemplatePath);
			}
			else
			{
				loader2 = new WebappTemplateLoader(this.context, "/dj/sharedtemplates/");
			}
			MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(new TemplateLoader[] {loader1,loader2});
			freemarkerCfg.setTemplateLoader(multiTemplateLoader);
	        Properties p = new Properties();   
	        try {
				p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("freemarker.properties"));   
				freemarkerCfg.setSettings(p);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (TemplateException e) {
				e.printStackTrace();
			}  

			Template template = freemarkerCfg.getTemplate(ftlName);
			template.setEncoding(encoding);
			this.request.setCharacterEncoding(encoding);
			this.response.setContentType("text/html; charset=" + encoding);
			String path = this.context.getRealPath(generatedFilePath);
			File dir = new File(path);
			if (!dir.exists())
			{
				dir.mkdirs();
			}
			buff = new BufferedWriter(new FileWriter(path + generatedFileName));
			File htmlFile = new File(path + File.separator + generatedFileName);
			out = new BufferedWriter(new OutputStreamWriter(
			  new FileOutputStream(htmlFile), encoding));
			template.process(map, out);
			out.flush();
			generatedFile = generatedFilePath + generatedFileName;
		} 
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} 
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		} 
		catch (TemplateException e)
		{
			e.printStackTrace();
		}
		finally
		{
		    try 
		    {
		    	if (null != buff)
		    	{
		    		buff.close();
		    	}
		    	if (null != out)
		    	{
					out.flush();
					out.close();
		    	}
			} 
		    catch (IOException e)
		    {
				e.printStackTrace();
			}
		}
	    return generatedFile;
	  }
	  
	  /**
	   * 处理模板文件并输出到响应端的流中
	   */
	  public void processUsingResponse()
	  {
		try 
		{
			Configuration freemarkerCfg = new Configuration();
			if (StringUtils.isBlank(templatePath))
			{
				templatePath = this.request.getContextPath() + "/templates/default";
			}
			else if (!templatePath.startsWith("/"))
			{
				templatePath = "/" + templatePath;
			}
			if (StringUtils.isBlank(encoding))
			{
				encoding = "GBK";
			}
			if (-1 == ftlName.lastIndexOf('.'))
			{
				ftlName = ftlName + ".ftl";
			}
			//加载模板所在路径
			WebappTemplateLoader loader1 = new WebappTemplateLoader(this.context, templatePath); 
			WebappTemplateLoader loader2 = null;
			if (StringUtils.isNotBlank(articleTemplatePath))
			{
				loader2 = new WebappTemplateLoader(this.context, articleTemplatePath);
			}
			else
			{
				loader2 = new WebappTemplateLoader(this.context, "/dj/sharedtemplates/");
			}
			MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(new TemplateLoader[] {loader1,loader2});
			freemarkerCfg.setTemplateLoader(multiTemplateLoader);
	        Properties p = new Properties();   
	        try {
				p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("freemarker.properties"));   
				freemarkerCfg.setSettings(p);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (TemplateException e) {
				e.printStackTrace();
			}  

			Template template = freemarkerCfg.getTemplate(ftlName);
			template.setEncoding(encoding);
			this.request.setCharacterEncoding(encoding);
			this.response.setContentType("text/html; charset=" + encoding);
			PrintWriter out = response.getWriter();
			template.process(map, out);
		} 
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} 
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		} 
		catch (TemplateException e)
		{
			e.printStackTrace();
		}
	  }
	  
	  
	  /**
	   * 处理模板文件并输出到控制台中
	   */
	  public void processUsingSysout()
	  {
		try 
		{
			Configuration freemarkerCfg = new Configuration();
			if (StringUtils.isBlank(templatePath))
			{
				templatePath = "/WEB-INF/templates";
			}
			else if (!templatePath.startsWith("/"))
			{
				templatePath = "/" + templatePath;
			}
			if (StringUtils.isBlank(encoding))
			{
				encoding = "GBK";
			}
			if (-1 == ftlName.lastIndexOf('.'))
			{
				ftlName = ftlName + ".ftl";
			}
			//加载模板所在路径
			WebappTemplateLoader loader1 = new WebappTemplateLoader(this.context, templatePath); 
			WebappTemplateLoader loader2 = null;
			if (StringUtils.isNotBlank(articleTemplatePath))
			{
				loader2 = new WebappTemplateLoader(this.context, articleTemplatePath);
			}
			else
			{
				loader2 = new WebappTemplateLoader(this.context, "/dj/sharedtemplates/");
			}
			MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(new TemplateLoader[] {loader1,loader2});
			freemarkerCfg.setTemplateLoader(multiTemplateLoader);

			Template template = freemarkerCfg.getTemplate(ftlName);
			template.setEncoding(encoding);
			this.request.setCharacterEncoding(encoding);
			this.response.setContentType("text/html; charset=" + encoding);
			template.process(map, new PrintWriter(System.out));
		} 
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} 
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		} 
		catch (TemplateException e)
		{
			e.printStackTrace();
		}
	  }
   
/**
    * 处理模板文件并将解析的后html内容以字符串方式返回给调用者
    */
   public String processReturnString()
   {
  try 
  {
   Configuration freemarkerCfg = new Configuration();
   if (StringUtils.isBlank(templatePath))
   {
    templatePath = "/WEB-INF/templates";
   }
   else if (!templatePath.startsWith("/"))
   {
    templatePath = "/" + templatePath;
   }
   if (StringUtils.isBlank(encoding))
   {
    encoding = "GBK";
   }
   if (-1 == ftlName.lastIndexOf('.'))
   {
    ftlName = ftlName + ".ftl";
   }
   //加载模板所在路径
   freemarkerCfg.setServletContextForTemplateLoading(this.context, templatePath);
         Properties p = new Properties();   
         try {
    p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("freemarker.properties"));   
    freemarkerCfg.setSettings(p);
   } catch (IOException e) {
    e.printStackTrace();
   } catch (TemplateException e) {
    e.printStackTrace();
   }  
   
   Template template = freemarkerCfg.getTemplate(ftlName);
   template.setEncoding(encoding);
   this.request.setCharacterEncoding(encoding);
   this.response.setContentType("text/html; charset=" + encoding);
   StringWriter sw = new StringWriter();
   template.process(map, new PrintWriter(sw));
   return sw.toString();
  } 
  catch (UnsupportedEncodingException e)
  {
   e.printStackTrace();
  } 
  catch (FileNotFoundException e)
  {
   e.printStackTrace();
  } 
  catch (IOException e) 
  {
   e.printStackTrace();
  } 
  catch (TemplateException e)
  {
   e.printStackTrace();
  }
  return "";
   }
}

使用方法为:

			Freemarker free = new Freemarker(context);//实例化模板类
			free.init(getRequest(), getResponse());//初始化请求和响应
			free.setFtlName(info.getIndexFtl());//设置模板的文件名
			free.setGeneratedFileName("index.html");//设置生成的静态html文件的名称
			free.setGeneratedFilePath(info.getGeneratedPath());//设置模板文件生成静态文件的路径
			free.setTemplatePath(info.getTemplatePath());//设置模板的加载路径
			free.setMap(root);//设置模板的数据模型
			String indexPath = free.process();//开始处理,返回结果,这里返回的就是静态html的相对路径



 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
commons-beanutils.jar Apache Commons包中的一个,包含了一些Bean工具类类。必须使用的jar包。 commons-collections.jar Apache Commons包中的一个,包含了一些Apache开发的集合类,功能比java.util.*强大 commons-lang.jar Apache Commons包中的一个,包含了一些数据类型工具类,是java.lang.*的扩展。必须使用的jar包。 commons-logging.jar: Apache Commons包中的一个,包含日志功能 commons-io.jar Apache Commons包中的一个,java.io.*的扩展,输入输出,支持文件上传 commons-fileupload.jar Apache Commons包中的一个,是一个通过Http接收上传的文件并处理结果文件的库 dom4j-1.4.jar 和 jaxen-1.1.1.jar 是一个Java的XML API,类似于jdom,用来读写XML文件的。Hibernate使用dom4j解析XML配置文件和XML映射元文件。必需的。 ehcache-1.2.jar Hibernate可以使用不同cache缓存工具作为二级缓存。EHCache是缺省的cache缓存工具。如果没有其它的可选缓存工具,则为必需的。 hibernate3.jar hibernate3的核心类库。 itext.jar 是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件为PDF文件。 iTextAsian.jar itext中关于亚洲编码的类库,在这里用于中文字体的输入。 junit.jar Junit包,当你运行Hibernate自带的测试代码的时候需要,否则就不用。 commons-digester.jar Apache Commons包中的一个,通过它可以很方便的解析xml文件生成java对象 aspectjrt.jar 和aspectjweaver.jar Annotation 方式实现 AOP commons-dbcp.jar commons-pool-1.2.jar DBCP数据库连接池 cglib-nodep-2.1_3.jar CGLIB是一个强大的高质量高性能的代码生成库,在运行时可以用它来扩展Java类 jfreechart-1.0.12.jar 使用java生成图表的工具 log4j-1.2.15.jar 通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件、甚至是套接口服务器 jxl-2.6.jar 通过java操作excel表格的工具类库 jta-1.1.jar Java事务API,为J2EE平台提供了分布式事务服务 lucene-core.jar 、lucene-highlighter.jar 、compass-index-patch.jar、 compass-2.1.0.jar 是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎 json-lib-2.2.3-jdk15.jar json和java的辅助工具 flexjson.jar java到json串的转换 gson-1.3.jar java到json串的转换 ognl-2.6.11.jar OGNL表达式所需要的包,支持EL htmlparser.jar 强大的html解析器 jcommon-1.0.15.jar 使用java生成图表的工具 freemarker-2.3.8.jar 模板相关操作需要包 struts2-core-2.0.14.jar struts2核心包 struts2-spring-plugin-2.0.14.jar struts2整合spring所需要的包 xwork-2.0.7.jar xwork核心包 antlr-2.7.6.jar 一个语言转换工具, Hibernate利用它实现 HQL 到 SQL 的转换模板相关操作需要包 javassist-3.9.0.GA.jar 代码生成工具 Hibernate用它在运行时扩展 Java类和实现,同cglib包 slf4j-api-1.5.8.jar和slf4j-log4j12-1.5.0.jar hibernate使用的一个日志系统 spring.jar spring核心包 spring-security-core-2.0.4.jar 和 spring-security-taglibs-2.0.4.jar

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值