velocity-1.7学习笔记

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

 

Velocity模板使用的赋值及流程控制语法:
VTL:
注释:
单行注释的前导符为“##”;多行注释则采用“#*”和“*#”符号

引用:
在VTL中有3种类型的引用:变量、属性和方法
变量引用的简略标记是由一个前导“$”字符后跟一个VTL标识符“Identifier”组成的。一个VTL标识符必须以一个字母开始(a...z或A...Z),剩下的字符将由以下类型的字符组成:
a.字母(a...z,A...Z)
b.数字(0...9)
c.连字符("-")
d.下划线("_")
给变量赋值有两种方法,
通过java代码给Context赋值,然后由Velocity引擎将Context与Template结合;
通过#set指令给变量赋值;

正式引用符(Formal Reference Notation):示例 ${purchaseMoney}

正式引用符多用在引用变量和普通文件直接邻近的地方

当Velocity遇到一个未赋值的引用时,会直接输出这个引用的名字。如果希望在没有赋值时显示空白,则可以使用安静引用符(Quiet Reference Notation)绕过Velocity的常规行为,以达到希望的效果。安静引符的前导字符为“$!变量名”

 

1.变量定义

变量名的有效字符集:

$ [ ! ][ { ][ a..zA..Z ][ a..zA..Z0..9-_ ][ } ]

Examples:

  • 一般方式: $mud-Slinger_9
  • 静态(输出原始字面): $!mud-Slinger_9
  • 正规格式: ${mud-Slinger_9}

http://www.cnblogs.com/netcorner/archive/2008/07/11/2912125.html



Velocity中加载vm文件的三种方式

 
velocitypropertiespath
Velocity中加载vm文件的三种方式:
  
方式一:加载classpath目录下的vm文件
Properties p =  new  Properties();
p.put( "file.resource.loader.class" ,
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader" );
Velocity.init(p);
...
Velocity.getTemplate(templateFile);
  
  
方式二:根据绝对路径加载,vm文件置于硬盘某分区中,如:d: //tree.vm
Properties p =  new  Properties();
p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH,  "d://" );
Velocity.init(p);
...
Velocity.getTemplate( "tree.vm" );
  
  
方式三:使用文本文件,如:velocity.properties,配置如下:
#encoding
input.encoding=UTF- 8
output.encoding=UTF- 8
contentType=text/html;charset=UTF- 8
不要指定loader.
 
  
再利用如下方式进行加载
Properties p =  new  Properties();
p.load( this .getClass().getResourceAsStream( "/velocity.properties" ));
Velocity.init(p);
...
Velocity.getTemplate(templateFile);
 
package  com.study.volicity;
 
import  java.io.IOException;
import  java.io.StringWriter;
import  java.util.Properties;
 
import  org.apache.velocity.app.Velocity;
import  org.apache.velocity.Template;
import  org.apache.velocity.VelocityContext;
 
public  class  Test {
     
 
     public  static  void  main(String args[])  throws  IOException {
 
         Properties pros =  new  Properties();
         pros.load(Test. class .getClassLoader().getResourceAsStream( "velocity.properties" ));
         Velocity.init(pros);
         VelocityContext context =  new  VelocityContext();
 
         context.put( "name" "Velocity" );
         context.put( "project" "Jakarta" );
 
         /* lets render a template 相对项目路径 */
         Template template = Velocity.getTemplate( "/view/header.vm" );
 
         StringWriter writer =  new  StringWriter();
 
         /* lets make our own string to render */
         template.merge(context, writer);
         System.out.println(writer);
     }
 
}
 
http://www.cnblogs.com/c-abc/p/4829084.html
 

 

package velocity;

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

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Properties;

/**
 * Created by 10159705 on 16-3-28.
 */
public class VelocityDemo {

    public static void main(String[] args) throws IOException {


        VelocityContext context = new VelocityContext();
        context.put("name", "VName");
        context.put("project", "JakProject");

        String path = VelocityDemo.class.getResource("/velocity/").getPath();//example2.vm
        System.out.println(path);
        Properties p = new Properties();
        p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, path);
        Velocity.init(p);


        Template template = Velocity.getTemplate("example2.xml", "GBK");
        Writer writer = new BufferedWriter(new FileWriter("result.xml"));
        template.merge(context, writer);
        writer.flush();
        writer.close();

    }
}

example2.xml

<?xml version="1.0" encoding="GB2312"?>
<root>
Hello from ${name} in the $!project project.
</root>




 

转载于:https://www.cnblogs.com/softidea/p/3890958.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值