Java 读取freemarker模板(html)转换成String

Java代码

package com.main.util;

import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Locale;

public class AppUtil implements ApplicationContextAware,ServletContextAware{
   
   private static final Logger logger = LoggerFactory.getLogger(AppUtil.class);
   
    
   @Resource 
   private ApplicationContext applicationContext;
   
   @Resource
   private ServletContext servletContext;
   
   private freemarker.template.Configuration freemarker = null;
   
   static class AppUtilHolder{
      static AppUtil instance = new AppUtil();
   }
   
   private AppUtil() {
      freemarker = new freemarker.template.Configuration();
      java.io.InputStream is = null;
      try {
         is = getClass().getResourceAsStream("/config/freemarker.properties");
         freemarker.setSettings(is);
         freemarker.setEncoding(Locale.CHINA, "UTF-8");
      } catch (Exception e) {
         logger.error(e.getMessage());
      } finally {
         try {
            if(is!=null){
               is.close();
            }
         } catch (Exception e) {
            logger.error(e.getMessage());
         }
      }
   }
   
   public static AppUtil getInstance() {
      return AppUtilHolder.instance;
   }
   
   @Override
   public void setServletContext(ServletContext servletContext) {
      logger.debug("Freemarker: Set servlet context for TemplateLoading.");
      freemarker.setServletContextForTemplateLoading(servletContext, "/");
   }

   public ServletContext getServletContext() {
      return servletContext;
   }
   
   @Override
   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
   
      
   }

   public ApplicationContext getApplicationContext() {
      return applicationContext;
   }
   
   public void destroy() {
      logger.debug("CableMIS AppUtil destroy.");
   }
   
   public freemarker.template.Configuration getFreemarker() {
      return freemarker;
   }

   /**
    * @param path html路径
    * @param model 写入html页面的数据
    * @param charset 编码格式(UTF-8)
    * @return
    * @throws Exception
    */
   public String renderHtml(String path, java.util.Map<String, Object> model, String charset) throws Exception {
       Writer out = new StringWriter();
           try {
               // 获取模板,并设置编码方式
               Template template = freemarker.getTemplate(path);
               template.setEncoding(charset);
               // 合并数据模型与模板
               template.process(model, out); //将合并后的数据和模板写入到流中,这里使用的字符流
               out.flush();
               return out.toString();
           } catch (Exception e) {
              logger.error(e.getMessage());
           } finally {
               try {
                   out.close();
               } catch (IOException ex) {
                  logger.error(ex.getMessage());
               }
           }
           return null;
   }
   
   public String renderHtml(String path, java.util.Map<String, Object> model, HttpServletResponse response)
         throws Exception {
      freemarker.template.Template tpl;
      try {
         tpl = freemarker.getTemplate(path);
      } catch (Exception e) {
         String lowerPath = path.toLowerCase();
         if (!path.equals(lowerPath))
            tpl = freemarker.getTemplate(lowerPath);
         else
            throw e;
      }
      response.setContentType("text/html;charset=UTF-8");
      
      tpl.process(model, response.getWriter());
      return null;

   }
}

freemarker.properties

classic_compatible=true
tag_syntax=auto_detect
#tag_syntax=square_bracket
default_encoding=UTF-8
url_escaping_charset=UTF-8
locale=zh_CN
#template_update_delay=5
datetime_format=yyyy-MM-dd HH:mm:ss
date_format=yyyy-MM-dd
time_format=HH:mm:ss
number_format=0.###
boolean_format=true,false
whitespace_stripping=true

转载于:https://my.oschina.net/u/3445245/blog/2045629

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值