天天看點

Velocity例子

import java.io.PrintWriter;

import java.io.StringWriter;

import java.util.Map;

import java.util.Properties;

import org.apache.commons.lang.ObjectUtils;

import org.apache.velocity.Template;

import org.apache.velocity.VelocityContext;

import org.apache.velocity.app.Velocity;

import org.apache.velocity.app.VelocityEngine;

import com.gzdec.common.config.AppConfig;

import com.gzdec.common.config.AppConfigException;

import com.gzdec.common.jdbc.core.DataAccessException;

/**

* velocity操作類

 * @author YangZhiFeng   

 * @version 1.0   

 * @created 2012-8-7 下午03:10:31  

 */   

public class VelocityUtil {

    /***

     * 生成模闆

     * @param filePath:生成的檔案路徑    vmPath:模闆所在全路徑    context:參數

     * @throws Exception

     * @throws DataAccessException

     */

    public void createVmByPath(String filePath,String vmPath,VelocityContext context) throws Exception{

        // 建立引擎 

        VelocityEngine ve=new VelocityEngine();  

        //設定模闆加載路徑,這裡設定的是class下  

        ve.setProperty(Velocity.RESOURCE_LOADER, "file");

        ve.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");

        ve.setProperty("file.resource.loader.path", ObjectUtils.toString(AppConfig.getProperty("rootPath")));

        //進行初始化操作  

        ve.init();

        try {

            //進行初始化操作

            ve.init();

            //加載模闆,設定模闆編碼

            Template t=ve.getTemplate(vmPath,"gbk");

            //設定輸出

            PrintWriter writer = new PrintWriter(filePath);

            //将環境資料轉化輸出

            t.merge(context, writer); 

            writer.close();  

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

     * @param filePath:生成的檔案路徑    fileName:模闆所在檔案夾名    vmName:模闆名稱        context:參數

    public void createVmByName(String filePath,String fileName,String vmName,VelocityContext context) throws Exception{

            Template t=ve.getTemplate(Constants.VM_TEMPLATE_PATH+"/"+fileName+"/"+vmName,"gbk");

     * 測試方法

     * @return

    public static void main(String[] args) throws Exception {

        VelocityUtil f = new VelocityUtil();

        VelocityContext context = new VelocityContext();

        context.put("name", "張三");

        context.put("project", "Jakarta");