Velocityに基づいて自分のテンプレートエンジンを開発します。

5467 ワード

Velocityはjavaベースのテンプレートエンジンです。誰でも簡単にテンプレート言語を使ってjavaコードによって定義されたオブジェクトを引用することに同意します。 
Velocityがweb開発に応用されると、インターフェース設計者はjavaプログラム開発者と同じようにMVCアーキテクチャに基づくウェブサイトを開発できます。つまり、ページ設計者はページの表示効果だけに注目して、javaプログラム開発者が業務ロジックコードに関心を持つことができます。Velocityはjavaコードをウェブページから分離してウェブサイトの長期メンテナンスに便利を提供しています。同じ時にもJSP、PHP、Freemarker以外にオプションの方案を提供してくれました。 
ほとんどの開発者は上記の部分だけを理解しています。即ち、VCのVとしてVelocityとSpringMVC、VelocityとStrutsを統合したデザインがあります。しかし、あまり注目されていません。Velocityはテンプレートエンジンとしての意味を持っています。テンプレートエンジンである以上、MVCの分野に限定されるべきではありません。
Velocityの能力はウェブサイトの開発のこの領域だけではなくて、たとえば、それはテンプレートからSQLとPostScript、XMLを生むことができて、それも1つの独立したツールとしてソースと報告を生むことができて、あるいはその他のシステムの集積コンポーネントとして使用します。
以下のコードは、私のVelocityに対するシンプルなパッケージです。Velocityを単独のコンポーネントとして使うことができます。少し豊かにすれば、私たちが適用するテンプレートエンジンになります。
コアコード:
package com.ths.platform.framework.template;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

public class VelocityParser
{
    //     
    private VelocityContext mainContext;
    //    
    private Template mainTemplate;
    //    
    private VelocityEngine velocityEngine;
    //         
    private  Properties properties;

    public static void main( String[ ] args ) {
        String filepath = "template/view.jsp";
        VelocityParser velocityParser = new VelocityParser( filepath );
        velocityParser.addToContext( "title" , "HelloWorld" );
        velocityParser.processTemplate( );
    }

    /**
     * @MethodName	: addToContext
     * @Description	:            
     * @param key
     * @param value
     */
    public void addToContext( String key, Object value ) {
        if ( mainContext == null )
        {
            mainContext = new VelocityContext( );
        }

        mainContext.put( key , value );
    }

    /**
     * @MethodName	: addToContext
     * @Description	:        
     * @param chainCtx
     */
    public void addToContext( VelocityContext chainCtx ) {
        mainContext = new VelocityContext( chainCtx );
    }

    /**
     * @MethodName	: processTemplate
     * @Description	:       
     */
    public void processTemplate() {
        try
        {
            BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( System.out ) );
            if ( mainTemplate != null )
            {
                mainTemplate.merge( mainContext , writer );
            }

            writer.flush( );
            writer.close( );
        }
        catch ( Exception ex )
        {
            ex.printStackTrace( );
        }
    }
    
    /**
     * @MethodName	: processTemplate
     * @Description	:      
     * @param destPath
     */
    public void processTemplate(String destPath) {
        try
        {
            OutputStream os = new FileOutputStream(destPath);
            OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");
            
            if ( mainTemplate != null )
            {
                mainTemplate.merge( mainContext , writer );
            }

            writer.flush( );
            writer.close( );
        }
        catch ( Exception ex )
        {
            ex.printStackTrace( );
        }
    }

    /**
     *              
     * @param templateFile
     */
    public VelocityParser( String templateFile ) {
         this(templateFile , null);
    }

    /**
     *             (  )       
     * @param templateFile
     * @param chainContext
     */
    public VelocityParser( String templateFile , VelocityContext chainContext ) {
        try
        {
            //      
            velocityEngine = new VelocityEngine( );
            
            //       
            properties = initProperties( );

            //       
            velocityEngine.init( properties );
            
            //      
            mainTemplate = velocityEngine.getTemplate( templateFile );
            
            //       
              if(chainContext!=null){

                //       

                mainContext = chainContext;

            }

        }
        catch ( Exception ex )
        {
            System.out.println( "Error processing template file: " + templateFile );
        }
    }

    /**
     * @MethodName	: initProperties
     * @Description	:        
     * @return
     */
    private Properties initProperties() {
        Properties properties = new Properties( );
        //   classpath       
        properties.setProperty( Velocity.FILE_RESOURCE_LOADER_PATH , Thread.currentThread( )
                .getContextClassLoader( ).getResource( "" ).getPath( ) );
        //        
        properties.setProperty( Velocity.INPUT_ENCODING , "utf-8" );
        properties.setProperty( Velocity.OUTPUT_ENCODING , "utf-8" );
        return properties;
    }

}
テンプレート:
 <table> 
 <tr><td>$title</td></tr> 
 </table>
メインメソッドを実行すると、テンプレートとパラメータを操作卓から出力して統合したデータを生成できます。
このコードがあったら、開発の過程で、繰り返しの労働に関わるだけでなく、どのような報告書を出力するかについても、テンプレートを取り出すことができるだけで、他の仕事は子牛を転がしましょう。