Velocity是由Apache软件组织提供的一项开放源码项目,它是一个基于Java的模板引擎。
通过Velocity模板语言(Velocity Template Language,VTL)定义模板(Template),并且在模板中不包含任何Java程序代码。
Java开发人员编写程序代码来设置上下文(Context),它包含了用于填充模板的数据。
Velocity引擎能够把模板和上下文合并起来,生成相关内容。
Velocity是一种后台代码和前台展示分离的一种设计。

velocity由以下几部分组成:

(1)指定runtime.log对应的日志文件(可选),Velocity.init()中使用;
(2)创建模板文件。默认以.vm结尾(模板的内容也可以写在代码中),由生成org.apache.velocity.Template对象的org.apache.velocity.app.Velocity.getTemplate(templateFile)使用; 
      Tips:模板文件要放在项目根目录下,否则不能正常加载
(3)模板中需要使用的动态数据。存放在org.apache.velocity.VelocityContext对象中,VelocityContext中使用map存放数据;
(4)输出最终生成的内容,javaapp和javaweb中不同

java app中

使用org.apache.velocity.Template.merge(...,context.., writer),这个方法有多个重载方法.其中writer是实现writer接口的io对象

            /*
             *  Now have the template engine process your template using the
             *  data placed into the context.  Think of it as a  'merge'
             *  of the template and the data to produce the output stream.
             */

javaweb中

访问servlet返回org.apache.velocity.Template对象,即可在浏览器中展示(可以认为是一个前端页面,内容浏览器传动解析)

 

其它:
使用log4j来输出velocity的日志:

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.Log4JLogChute;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

/**
 *  Simple example class to show how to use an existing Log4j Logger
 *  as the Velocity logging target.
 */
public class Log4jLoggerExample
{
    public static String LOGGER_NAME = "velexample";

    public static void main( String args[] )
        throws Exception
    {
        /*
         *  configure log4j to log to console
         */
        BasicConfigurator.configure();

        Logger log = Logger.getLogger(LOGGER_NAME);

        log.info("Hello from Log4jLoggerExample - ready to start velocity");

        /*
         *  now create a new VelocityEngine instance, and
         *  configure it to use the logger
         */
        VelocityEngine ve = new VelocityEngine();

        ve.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
                       "org.apache.velocity.runtime.log.Log4JLogChute");

        ve.setProperty(Log4JLogChute.RUNTIME_LOG_LOG4J_LOGGER, LOGGER_NAME);

        ve.init();

        log.info("this should follow the initialization output from velocity");
    }
}
View Code

相关文章:

  • 2021-10-21
  • 2022-12-23
  • 2021-05-15
  • 2021-09-20
  • 2021-09-09
  • 2022-01-29
  • 2021-11-05
  • 2022-02-16
猜你喜欢
  • 2021-12-22
  • 2021-10-03
  • 2021-09-11
  • 2021-09-27
  • 2022-02-15
  • 2022-03-04
  • 2021-08-31
相关资源
相似解决方案