VelocityEngine

来源:互联网 发布:2017淘宝图片尺寸要求 编辑:程序博客网 时间:2024/06/05 03:13

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和使用方式是类似的。都极其简单。


原创粉丝点击