2007年12月17日月曜日

[JAVA>Velocity, Template]customization how to convert String to Template Object

References
  1. Apache Velocity Home: http://velocity.apache.org/
Description
I added following customization logic which convert String java object to Velocity Template object because I sometimes needed template object dynamically without creating template file.
(Please let me know if you have any other good ideas.)

Customization Example Steps
  1. get Velocity Source code from velocity.apache.org site.
  2. open org.apache.velocity.Template.java file.
  3. add java class import statements in Template.java
    import org.apache.velocity.runtime.RuntimeSingleton;
    import org.apache.velocity.runtime.RuntimeConstants;
    import java.io.StringReader;
  4. add customized constructor function of Template object as follows.
    /*
    customized constructor which convert String Object to Template Object.
    @param pTemplateName is an template name
    @param pTemplateString is String object you want to render
    @return a velocity template object.
    */
    public Template(String pTemplateName,String pTemplateString)
    throws Exception
    {
    //Initialization
    RuntimeSingleton.init();

    setRuntimeServices(RuntimeSingleton.getRuntimeServices());
    setName(pTemplateName);
    //set encodeing if you need
    //setEncoding(RuntimeConstants.ENCODING_DEFAULT);

    data = null;
    errorCondition = null;
    StringReader stringReader=null;
    BufferedReader bufferedReader=null;

    try{
    stringReader=new StringReader(pTemplateString);
    bufferedReader=new BufferedReader(stringReader);

    data = rsvc.parse(bufferedReader,name);
    initDocument();
    }catch(Exception e){
    errorCondition=new Exception("Error occured while initializaing String Template, customization");
    throw errorCondition;
    }finally{
    if(stringReader!=null){
    stringReader.close();
    }
    if(bufferedReader!=null){
    bufferedReader.close();
    }
    }
    }
    /*
    End of Customization
    */
  5. compile new java file.
how to use this customization
String testTemplate="Velocity Template Test";
Template template=new Template("TemplateName",testTemplate);

0 件のコメント: