前言
关于velocity与SpringMVC的配置请参考前一篇文章,此处不再介绍。velocity作为Java模版引擎的主要目的是为了允许任何人使用简单而强大的模板语言来引用定义在Java代码中的对象。在velocity文件中可以给该页面指定模版布局,从而节省了大量的时间去写通用的模版布局。可以定义变量,与Java方法进行交互。
定义一个layout模版
在上一篇文章中提到了配置默认模版,当然也可以不使用默认模版即在要用到的页面的最上端写上
#set($layout='layout/yourlayout.vm')
那么如何定义一个layout,看下面的例子:
html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
$!page_title 测试layout页面$screen_content
那么$screen_content所在的位置即是你所打开页面将要占用的位置。
定义一个变量
#set($var='xxxx')
##输出上面的变量直接使用$var
魂环数组或者list
#foreach($ele in $list)
output element:$ele
#end
条件判断
#if($var=='xxxx')
it is right
#elseif($var=='')
sorry
#else
it is wrong
#end
内置对象
类似于JSP,velocity也有自己的内置对象,如$request,$response,$session这样以来我们就可以将Java对象request和response以及session里的东西轻而易举的展现在web页面里。
自定义标签(指令)
velocity同时也支持自定义标签,或者称为指令。如果查看velocity的源码就会发现有个directive.properties
directive.1=org.apache.velocity.runtime.directive.Foreach
directive.2=org.apache.velocity.runtime.directive.Include
directive.3=org.apache.velocity.runtime.directive.Parse
directive.4=org.apache.velocity.runtime.directive.Macro
directive.5=org.apache.velocity.runtime.directive.Literal
directive.6=org.apache.velocity.runtime.directive.Evaluate
directive.7=org.apache.velocity.runtime.directive.Break
directive.8=org.apache.velocity.runtime.directive.Define
directive.9=org.apache.velocity.runtime.directive.Stop
这里正是velocity当前所提供的9个标签(指令),下面我们新添加一个指令say
#say("hello")
java代码实现
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.directive.Directive;
import org.apache.velocity.runtime.parser.node.Node;
import org.apache.velocity.runtime.parser.node.SimpleNode;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.citrus.service.template.TemplateService;
import com.alibaba.click.util.HostUtil;
public class Say extends Directive{
@Autowired
TemplateService templateService;
private static final VelocityEngine velocityEngine = new VelocityEngine();
@Override
public String getName() {
return "say";
}
@Override
public int getType() {
return LINE;
}
@Override
public boolean render(InternalContextAdapter context, Writer writer,
Node node) throws IOException, ResourceNotFoundException,
ParseErrorException, MethodInvocationException {
SimpleNode sn = (SimpleNode) node.jjtGetChild(0);
writer.write((String)sn.value(context));
return true;
}
}
接下来就可以在velocity.properties文件里添加上
say=cn.buglife.demo.msv.directive.Say