velocity簡單實現

1、所需jar包commons-collections-3.2.1.jar、velocity-1.7.jar、velocity-1.7-dep.jar

2、編寫一個VelocityTest.java文件,內容如下:

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

public class VelocityTest {
    public static void main(String[] args) {
        //獲取velocity引擎
        VelocityEngine ve = new VelocityEngine();
        //項目的路徑
        //TODO=======需要自己修改========
        String path = "D:\\workspace\\VelocityTest01\\WebContent\\WEB-INF";
        //設定velocity引擎加載的路徑
        ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
        //設定velocity的輸入 輸出字符編碼
        ve.setProperty(Velocity.INPUT_ENCODING, "GBK");
        ve.setProperty(Velocity.OUTPUT_ENCODING, "GBK");
        try {
            //初始化引擎
            ve.init();
            //獲取模板
            Template template = ve.getTemplate("hello.vm");
            //velocity上下文
            VelocityContext root = new VelocityContext();
            //此處的name跟vm文件中的${name}中的name必須一致
            root.put("name", "world");
            //輸出路徑,查看結果是否正確
            String outpath = "e:/helloworld.html";
            Writer mywriter = new PrintWriter(new FileOutputStream(new File(
                    outpath)));
            template.merge(root, mywriter);
            mywriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
3、在當前目錄下面創建一個hello.vm文件,內容如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>New Document</TITLE>
</HEAD>
<BODY>hello,${name}!
</BODY>
</HTML>

4、運行下ok

有問題可以發送我郵箱[email protected]

發佈了13 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章