java 通过模板封装字符串的方法

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

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

public static final String READ_ECM_Xml="<?xml version='1.0' encoding='UTF-8'?><root><BASE_DATA><USER_CODE>${usercode}</USER_CODE><USER_NAME>${username}</USER_NAME><USER_ORG_CODE>${userorgcode}</USER_ORG_CODE><USER_SUBORG_CODE>${usersuborgcode}</USER_SUBORG_CODE><ORG_CODE>${orgcode}</ORG_CODE><COM_CODE>${comcode}</COM_CODE><ORG_NAME>${orgname}</ORG_NAME><ROLE_CODE>RYX_JYCL</ROLE_CODE><SECURITY_INFO><SYSTEM_ID>27</SYSTEM_ID><STR_TXT>${strtxt}</STR_TXT><STR_MTXT>${strmtxt}</STR_MTXT></SECURITY_INFO></BASE_DATA><META_DATA><BATCH><APP_CODE>CL_RYX</APP_CODE><APP_NAME>人意险理赔</APP_NAME><ORG_CODE>${orgcode2}</ORG_CODE><COM_CODE>${comcode2}</COM_CODE><BUSI_NO>${busino}</BUSI_NO><INS_TYPE></INS_TYPE><SYSTEM_ID>27</SYSTEM_ID></BATCH></META_DATA></root>";

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

String context=XMLContext.READ_ECM_Xml;
  
  Map<String,String> map=new HashMap<String,String>();
  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<String, Object> model = new HasMap<String, Object>();
  model.put("amountChinese", MoneyUtil.toChinese(nvl(p10PrintInfo.getTotalAmount(),"0")));//大写金额
  
  String tableStr=freemarkManager.fltTemplateIntoString("p10_common_accountinfo.ftl", model);

<!-- 配置freeMarker的模板路径 -->
 <bean id="freemarkerConfig"
  class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
  <property name="templateLoaderPath">
   <value>classpath:tlx/freemarkTemplate</value>
  </property>
  <property name="freemarkerVariables">
   <map>
    <entry key="xml_escape" value-ref="fmXmlEscape" />
   </map>
  </property>
  <property name="freemarkerSettings">
   <props>
    <prop key="default_encoding">UTF-8</prop>
    <prop key="classic_compatible">true</prop>
    <prop key="number_format">#.##</prop>
   </props>
  </property>
  <!--property name="freemarkerSettings" ref="freemarkerConfiguration"/ -->
 </bean>
  <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
</beans>

猜你喜欢

转载自huttoncs.iteye.com/blog/2266558