Velocity 是如何工作的呢? 虽然大多 Velocity 的应用都是基于 Servlet 的网页制作。但是为了说明 Velocity 的使用,我决定采用更通用的 Java application 来说明它的工作原理。
似乎所有语言教学的开头都是采用 HelloWorld 来作为第一个程序的示例。这里也不例外。
任何 Velocity 的应用都包括两个方面: 第一是: 模板制作,在我们这个例子中就是 hellosite.vm: 它的内容如下(虽然不是以 HTML 为主,但是这很容易改成一个 html 的页面) Hello $name! Welcome to $site world! 第二是 Java 程序部分: 下面是 Java 代码import java.io.StringWriter; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext;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", "Eiffel Qiu"); context.put("site", "http://www.eiffelqiu.com"); /* now render the template into a StringWriter */ StringWriter writer = new StringWriter(); t.merge( context, writer ); /* show the World */ System.out.println( writer.toString() ); } } 将两个文件放在同一个目录下,编译运行,结果是:
Hello Eiffel Qiu! Welcome to http://www.eiffelqiu.com world
为了保证运行顺利,请从 Velocity 的网站 http://jakarta.apache.org/velocity/ 上下载 Velocity 的运行包,将其中的 Velocity Jar 包的路径放在系统的 Classpath 中,这样就可以编译和运行以上的程序了。
出处:牧羊人手记
责任编辑:蓝色
上一页 网站制作的模式 下一页 Velocity 的工作原理:
◎进入论坛网络编程版块参加讨论
|