概述:
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