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

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

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

public static final String READ_ECM_Xml="${usercode}${username}${userorgcode}${usersuborgcode}${orgcode}${comcode}${orgname}RYX_JYCL27${strtxt}${strmtxt}CL_RYX人意险理赔${orgcode2}${comcode2}${busino}27";

 

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

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

 

 


   class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
  
   classpath:tlx/freemarkTemplate
  

  
   
    
   

  

  
   
    UTF-8
    true
    #.##
   

  

  
 

  

 

你可能感兴趣的:(java)