Velocity模板引擎

來源:互聯網
上載者:User

package zoer;

import java.io.StringWriter;

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

public class HelloWorld {
    public static void main(String[] args) throws Exception {
        /* first, get and initialize an engine */
        VelocityEngine ve = new VelocityEngine();
        ve.init();
        /* next, get the Template */
        Template t = ve.getTemplate("hellosite.vm");
        /* create a context and add data */
        VelocityContext context = new VelocityContext();
        context.put("name", "mason");
        context.put("site", "Naughty 's");
        /* now render the template into a StringWriter */
        StringWriter writer = new StringWriter();
        t.merge(context, writer);
        /* show the World */
        System.out.println(writer.toString());
    }
}

在項目根目錄下建立一個hellosite.vm,內容:

Hello $name!   Welcome to $site world!

執行上面java代碼,則會產生響應的html代碼。這裡只是 簡單一實例。並不是web工程。

簡單看了一下velocity模板引擎,其優勢是,拋棄了jsp,雖然jsp是J2EE的一部分,但是J2EE並不一定使用jsp,也可以使用velocity等這類模板引擎,同樣可以實現MVC,將代碼邏輯和頁面展現分開。

ps:前面學習了Django架構之後,再來看velocity模板引擎,感覺他們的Template和使用方式是類似的。都極其簡單。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.