一.内置对象(没有配置toolbox情况)
1.HttpServletRequest -------------------------$request
2.HttpServletResponse -----------------------$response
3.HttpSession ----------------------------------$session
二.layout
1.http://qieqie.iteye.com/blog/65028
三.vm语法
1.parse与include
parse-------动态包含vm文件,文件间可共享vm变量
include-----静态引入,不对vm表达式做解析
jsp中的
2.减法运算
#set($index=$index-1) ##这条语法会出错,改成如下:
#set($index=$index - 1) ##在减号前后各加一个空格
3.判断字符是否相等
#if($a==$b)success#end ##如果$a或$b为空,这条语句有语法错误,改成如下: #if("$a"=="$b")success#end 或者 #if($a&&$b&$a==$b)success#end
4.javascript中使用vm变量
5. foreach循环的counter(循环次数计数)
在velocity.properties中有一段配置
directive.foreach.counter.name = velocityCount ##定义变量名称
directive.foreach.counter.initial.value = 1 ##定义计算从1开始累加
例如:
#foreach($n in [1..10]) #if($velocityCount==$n)计数开始$velocityCount#end #end
四.模板的解析
1.模板文件的merge
StringWriter writer = new StringWriter();
Map context=new HashMap();
context.put("vm_prop1","12");
VelocityContext model = new VelocityContext(context);
model.put("vm_prop2", "14");
try {
Template tpl = Velocity.getTemplate("portal.vm");
tpl.merge(model, writer);
writer.close();
} catch (Exception e) {
log.error("Can't merge portal.vm", e);
}
log.info(writer.toString);
对portal.vm中的vm_prop1和vm_prop2两个变量赋值并解析返回writer
2.字符串的merge
public static boolean evaluate(org.apache.velocity.context.Context context, Writer writer, String logTag, Reader reader) throws ParseErrorException, MethodInvocationException, ResourceNotFoundException, IOException {
SimpleNode nodeTree = null;
try {
nodeTree = RuntimeSingleton.parse(reader, logTag, false);
} catch (ParseException pex) {
throw new ParseErrorException(pex.getMessage());
}
if (nodeTree != null) {
InternalContextAdapterImpl ica = new InternalContextAdapterImpl(context);
ica.pushCurrentTemplateName(logTag);
try {
try {
nodeTree.init(ica, RuntimeSingleton.getRuntimeServices());
} catch (Exception e) {
RuntimeSingleton.error("Velocity.evaluate() : init exception for tag = " + logTag + " : " + e);
}
nodeTree.render(ica, writer);
} finally {
ica.popCurrentTemplateName();
}
return true;
}
return false;
}
StringReader reader = new StringReader("#foreach($n in $list)
Properties props = new Properties();
try {
File conf = new File(event.getServletContext().getRealPath("WEB-INF/velocity.properties"));
props.load(new FileInputStream(conf));
}catch (Exception e) {
e.printStackTrace();
}
try {
Iterator