概述:
velocity是一个典型的model和view分离设计思想的体现,因此其概念定义的几个主要元素和mvc中的概念也有一定的隐射关系。
比较重要的几个概念:
1.VelocityContext:velocity上下文,用来保存数据用的,主要是工程师书写代码是放数据用的,提供给模板使用
2.Template:模板,设计师设计的页面的加载器,具体的数据则由VelocityContext中获取,template.merge是将数据和vm模板合并输出具体的结果
3.vm模板:设计师设计的页面,包含样式以及替换的数据标识等内容,具体内容如下:
3.1.引用(reference):java代码中put到Velocity的变量替换符,有三种引用(reference):变量($variable)、属性($variable.attribute)、方法($variable.method())
3.2.指令(directives):指令主要是允许页面设计人员进行变量和脚本控制,以及自定义变量,常见的指令有:
3.3.宏定义(macros):当重复vm模板代码中存在着一些共性的代码,就可以自定义一个宏,减少代码量循环指令:# [ { ] foreach [ } ] ( $ref in arg ) statement # [ { ] end [} ]
条件判断指令:# [ { ] if [ } ] ( [condition] ) [output] [ # [ { ] elseif [ } ] ( [condition] ) [output] ]* [ # [ { ] else [ } ] [output] ] # [{ ] end [ } ]
包含指令:# [ { ] include [ } ] ( arg[ arg2 ... argn] )
演示代码:
HelloWorld.java
- package com.wm.mad.tmp;
- import java.io.StringWriter;
- import org.apache.velocity.Template;
- import org.apache.velocity.VelocityContext;
- import org.apache.velocity.app.VelocityEngine;
- import org.apache.log4j.Logger;
- import org.apache.log4j.PropertyConfigurator;
- public class HelloWorld {
- static Logger logger = Logger.getLogger(HelloWorld.class);
- public static void main(String[] args) throws Exception {
- PropertyConfigurator.configure("log4j.properties");
- VelocityEngine ve = new VelocityEngine();
- ve.init("velocity.properties");
- Template template = ve.getTemplate("helloWorld.vm");
- VelocityContext context = new VelocityContext();
- context.put("name", "madding");
- context.put("password", "madding");
- StringWriter writer = new StringWriter();
- template.merge(context, writer);
- System.out.println(writer.toString());
- if(logger.isInfoEnabled()) {
- logger.info("operator is success");
- }
- }
- }
helloWorld.vm:
- 你的
- 名字是:$name
- 密码是:$password
velocity.properties:
- input.encoding=GBK
- output.encoding=GBK
- velocimacro.permissions.allow.inline=true
- runtime.log = d:/log/velocity.log
log4j.properties:
- log4j.rootLogger=INFO,logfile
- log4j.appender.logfile=org.apache.log4j.RollingFileAppender
- log3j.appender.logfile.Threshold=INFO
- log4j.appender.logfile.File=d:/log/velocity_use.log
- log4j.appender.logfile.Append=true
- log4j.appender.logfile.MaxFileSize=1MB
- log4j.appender.logfile.MaxBackupIndex=3
- log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
- log4j.appender.logfile.layout.ConversionPattern =%d %p [ %c] - %m %n %d