zoukankan      html  css  js  c++  java
  • 一个Velocity Template Language学习的框架

    Velocity Template Language(VTL)使得数据展示和后台代码的开发分离开来,最初用在基于servlet的网站开发上,它的这一特性使得它在应付MVC Web开发模式时显得尤其合适。之前在项目上修修改改,一直没有对VTL的原理进行分析,这次有空,参考了网上一个好的VTL框架学习一下。当然,这个框架只是个Helloworld程序。

    对于任意的一个VTL应用来说,分为两部分:

    • .vm文件
    • java 文件:用来生成.vm文件中需要的变量

    举个例子来说(HelloWorld)

    helloworld.vm

    Hello $name!  Welcome to Velocity!

    HelloWorld.java

    package com.lipan.velocity;
     
    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( "helloworld.vm" );
            /*  create a context and add data */
            VelocityContext context = new VelocityContext();
            context.put("name", "World");
            /* now render the template into a StringWriter */
            StringWriter writer = new StringWriter();
            t.merge( context, writer );
            /* show the World */
            System.out.println( writer.toString() );     
        }
    }

    需要注意的问题

    在maven建立工程的时候,要引入velocity和velocity-tools的依赖文件,注意velocity-tools最好不要选择source版的,否则可能出现引入不正确的情况,pom.xml文件的依赖如下:

    <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity</artifactId>
                <version>1.7</version>
                <classifier>sources</classifier>
            </dependency>
            <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity-tools</artifactId>
                <version>2.0</version>
            </dependency>

    代码

    工程文件在github上,链接是:https://github.com/obalama/VelocityHelloworld.git

    代码依赖于maven

  • 相关阅读:
    #include< >和#include“ ”的区别
    第2章 基础语法 -- 运算符
    hive on spark的安装及问题
    第2章 Python基础语法 -- 数据类型
    第2章 Python基础语法--Hello python
    IT资源专业搜索-www.easysoo.cn
    学习英语
    zookeeper 安装
    Hadoop2.6 Ha 安装
    Hadoop平台安装前准备
  • 原文地址:https://www.cnblogs.com/obama/p/3838402.html
Copyright © 2011-2022 走看看