---
title: "java 通过模板封装字符串的方法"
author: "huttoncs"
date: "2015-12-25T11:11:03Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2015-12-25T11:11:03Z"
id: 2266558
url: "https://huttoncs.iteye.com/blog/2266558"
---

最近写接口经常用到字符串报文封装，这里汇总一下用到的几种方法：

1、直接将模板定义在常量字符串中

public static final String READ\_ECM\_Xml="&lt;?xml version='1.0' encoding='UTF-8'?&gt;&lt;root&gt;&lt;BASE\_DATA&gt;&lt;USER\_CODE&gt;${usercode}&lt;/USER\_CODE&gt;&lt;USER\_NAME&gt;${username}&lt;/USER\_NAME&gt;&lt;USER\_ORG\_CODE&gt;${userorgcode}&lt;/USER\_ORG\_CODE&gt;&lt;USER\_SUBORG\_CODE&gt;${usersuborgcode}&lt;/USER\_SUBORG\_CODE&gt;&lt;ORG\_CODE&gt;${orgcode}&lt;/ORG\_CODE&gt;&lt;COM\_CODE&gt;${comcode}&lt;/COM\_CODE&gt;&lt;ORG\_NAME&gt;${orgname}&lt;/ORG\_NAME&gt;&lt;ROLE\_CODE&gt;RYX\_JYCL&lt;/ROLE\_CODE&gt;&lt;SECURITY\_INFO&gt;&lt;SYSTEM\_ID&gt;27&lt;/SYSTEM\_ID&gt;&lt;STR\_TXT&gt;${strtxt}&lt;/STR\_TXT&gt;&lt;STR\_MTXT&gt;${strmtxt}&lt;/STR\_MTXT&gt;&lt;/SECURITY\_INFO&gt;&lt;/BASE\_DATA&gt;&lt;META\_DATA&gt;&lt;BATCH&gt;&lt;APP\_CODE&gt;CL\_RYX&lt;/APP\_CODE&gt;&lt;APP\_NAME&gt;人意险理赔&lt;/APP\_NAME&gt;&lt;ORG\_CODE&gt;${orgcode2}&lt;/ORG\_CODE&gt;&lt;COM\_CODE&gt;${comcode2}&lt;/COM\_CODE&gt;&lt;BUSI\_NO&gt;${busino}&lt;/BUSI\_NO&gt;&lt;INS\_TYPE&gt;&lt;/INS\_TYPE&gt;&lt;SYSTEM\_ID&gt;27&lt;/SYSTEM\_ID&gt;&lt;/BATCH&gt;&lt;/META\_DATA&gt;&lt;/root&gt;";

 

可以通过如下两种方式进行封装：

String context=XMLContext.READ\_ECM\_Xml;  
    
  Map&lt;String,String&gt; map=new HashMap&lt;String,String&gt;();  
  map.put("usercode","1");  
  map.put("username","2");  
  map.put("userorgcode","3");  
  map.put("usersuborgcode","4");  
  map.put("orgcode","5");  
  map.put("comcode","6");  
  map.put("orgname","7");  
  map.put("strtxt","8");  
  map.put("strmtxt","9");  
  map.put("orgcode2","10");  
  map.put("comcode2","11");  
  map.put("busino","12");  
/\** ------------- 方法一 ----------------\*/

  try {  
   VelocityContext velocityContext = new VelocityContext(map);   
         StringWriter result = new StringWriter();   
          
         VelocityEngine engine = new VelocityEngine();  
   try {   
             engine.init();   
         } catch (Exception e) {   
             e.printStackTrace();  
         }  
          
         engine.evaluate(velocityContext, result,"test", context);   
    
         String returnString = result.toString();   
         logger.info("returnString:"+returnString);  
  } catch (ParseErrorException e) {  
   // TODO Auto-generated catch block  
   e.printStackTrace();  
  } catch (MethodInvocationException e) {  
   // TODO Auto-generated catch block  
   e.printStackTrace();  
  } catch (ResourceNotFoundException e) {  
   // TODO Auto-generated catch block  
   e.printStackTrace();  
  }

/\** ------------- 方法二 ----------------\*/

String patternString = "[\\\\$\\\\](){(" + StringUtils.join(map.keySet(), "|") + ")\\\\}";  
   Pattern pat = Pattern.compile(patternString);  
         Matcher matcher = pat.matcher(context);  
          
         StringBuffer sb = new StringBuffer();  
          
          
         while (matcher.find()) {  
          matcher.appendReplacement(sb, map.get(matcher.group(1)));  
         }   
         matcher.appendTail(sb);

 

          sb.toString();

}

 

2、可以通过将模板定义在文件中的方式，这种方式同样有两种方法

方法一是通过Velocity.mergeTemplate()的方法这里就不写了，网上有很多，我这里大概写一下

      Template template = Velocity.getTemplate(fileName);  
        VelocityContext context = new VelocityContext();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  
        PrintWriter dw = new PrintWriter(outputStream);  
        Velocity.mergeTemplate(template.getName(), charset, context, dw);  
        outputStream.close();  
        dw.close();

        return outputStream.toByteArray();

方法二是同过freemarker.template.Template的方法

@Service  
public class FreemarkManager {  
 private static Logger log = LoggerFactory.getLogger(FreemarkManager.class);  
 @Autowired  
 private FreeMarkerConfigurer freemarkerConfig;  
   
 public String fltTemplateIntoString(String templateFileName, Object model) {  
  // 保证Configuration能初始化  
  String templateString = null;  
  try {  
   freemarkerConfig.afterPropertiesSet();  
   Configuration config = freemarkerConfig.getConfiguration();  
   Template template = config.getTemplate(templateFileName);  
   templateString = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);  
  } catch (IOException e) {  
   log.error("Freemark模板"+templateFileName+"获取IOException异常:"  +e.getMessage());  
     
  } catch (TemplateException e) {  
   log.error("Freemark模板"+templateFileName+"TemplateException异常:" +e.getMessage());  
  }  
  return templateString;

 }  
}

 

service 的调用：

Map&lt;String, Object&gt; model = new HasMap&lt;String, Object&gt;();  
  model.put("amountChinese", MoneyUtil.toChinese(nvl(p10PrintInfo.getTotalAmount(),"0")));//大写金额  
    
  String tableStr=freemarkManager.fltTemplateIntoString("p10\_common\_accountinfo.ftl", model);

 

 

&lt;!-- 配置freeMarker的模板路径 --&gt;  
 &lt;bean id="freemarkerConfig"  
  class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"&gt;  
  &lt;property name="templateLoaderPath"&gt;  
   &lt;value&gt;classpath:tlx/freemarkTemplate&lt;/value&gt;  
  &lt;/property&gt;  
  &lt;property name="freemarkerVariables"&gt;  
   &lt;map&gt;  
    &lt;entry key="xml\_escape" value-ref="fmXmlEscape" /&gt;  
   &lt;/map&gt;  
  &lt;/property&gt;  
  &lt;property name="freemarkerSettings"&gt;  
   &lt;props&gt;  
    &lt;prop key="default\_encoding"&gt;UTF-8&lt;/prop&gt;  
    &lt;prop key="classic\_compatible"&gt;true&lt;/prop&gt;  
    &lt;prop key="number\_format"&gt;#.##&lt;/prop&gt;  
   &lt;/props&gt;  
  &lt;/property&gt;  
  &lt;!--property name="freemarkerSettings" ref="freemarkerConfiguration"/ --&gt;  
 &lt;/bean&gt;  
  &lt;bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/&gt;  
&lt;/beans&gt;