Java 讀取freemarker模板(html)轉換成String

Java代碼html

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.propertiesjava

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
相關文章
相關標籤/搜索