Freemark使用实例

 

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.log4j.Logger;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModelException;

 /**
 * Add one sentence class summary here.
 * Add class deion here.
 *
 * @author AllenJ
 * @version 1.0, 2008-1-2
 * @since 1.0
 */
public class SoapRequest {
  private static Logger logger = Logger.getLogger(SoapRequest.class);

 public SoapRequest() {
  logger.debug("SoapRequest()");
  // TODO Auto-generated constructor stub
 }
public String init(String orderId,String name){
 //配置对象
  Configuration cfg = new Configuration();
 
  try {
        //Set directory for loading template
  cfg.setDirectoryForTemplateLoading(new File("template/"));
 } catch (IOException e) {
  logger.error("SR-INIT-1001:"+"Set directory error,for "+e.getMessage());
 }
 cfg.setObjectWrapper(new DefaultObjectWrapper());
 
 //共享变量是指所有模板都能访问的变量,在configuration中设置, 数据模型中rootMap的变量将会隐藏同名的共享变量。
  try {
  cfg.setSharedVariable("constant_1", "Constant_1");
 } catch (TemplateModelException tme) {
  logger.error("SR-INIT-1002:"+"Set shared variable error,for "+tme.getMessage());
 }


  Map rootMap = new HashMap();
  rootMap.put("orderID", orderId);
  rootMap.put("name",name);
 
 
  //得到模板对象,Configuration对Template对象进行缓存。
  Template template=null;
  try {
   template = cfg.getTemplate("soapRequest.ftl", Locale.US);
 } catch (IOException e) {
  logger.error("SR-INIT-1003:"+"get template fail,for "+e.getMessage());
 }
 
 //合并模板和数据模型
 StringWriter writer = new StringWriter();
 try {
  template.process(rootMap, writer);
 } catch (TemplateException e) {
  logger.error("SR-INIT-1004:"+"process template data fail,for "+e.getMessage());
  e.printStackTrace();
 } catch (IOException e) {
  logger.error("SR-INIT-1005:"+"IO fail,for "+e.getMessage());
 }
 writer.flush();
 try {
  writer.close();
 } catch (IOException e) {
  logger.error("SR-INIT-1006:"+"can't close the IO Stream,for "+e.getMessage());
 }
 return writer.toString();
}
 

 public static void main(String[] args) {
  SoapRequest soapRequest=new SoapRequest();
  logger.info(soapRequest.init("007","Allen"));

 }

}

示意图如下:

输出结果:

<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
 <SOAP:Body>
        <getORDER>
         <ORDERID>007</ORDERID>
         <NAME>Allen</NAME>
        </getORDER>
        <getConstant>
         <CONSTANT>Constant_1</CONSTANT>
        </getConstant>
 </SOAP:Body>
</SOAP:Envelope>

 

源文件

你可能感兴趣的:(Freemark使用实例)