1
#include只包含不render
#parse包含并render
2
定义
#macro(aaa)
....
#end
使用
#aaa()
3
#foreach($i in [0..3])
$obj.name
#end
此时obj.name被调用3次
4 application示例
代码
public class ApplicationTest {
public static void main(String[] args) throws Exception {
Velocity velocity = new Velocity();
velocity.init();
Template tp = velocity.getTemplate("helloapp.vm");
VelocityContext context = new VelocityContext();
context.put("name","severus");
StringWriter writer = new StringWriter();
tp.merge(context, writer);
System.out.println(writer.toString());
}
}
模板
Hello world,$name!
5 web示例
servlet
@SuppressWarnings("deprecation")
public class MyVelocityServlet extends VelocityServlet {
private static final long serialVersionUID = 1L;
@Override
protected Properties loadConfiguration(ServletConfig config)
throws IOException, FileNotFoundException {
Properties properties = new Properties();
String path = config.getServletContext().getRealPath("/");
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
properties.setProperty("runtime.log", path + "velocity.log");
return properties;
}
@Override
public Template handleRequest(HttpServletRequest request,
HttpServletResponse response, Context ctx) throws Exception {
Velocity.init();
Template template = Velocity.getTemplate("helloweb.vm");
ctx.put("name", "severus");
return template;
}
}
模板
<html>
<body >
Hello, $name
</body>
</html>
web.xml
<servlet> <servlet-name>myVelocityServlet</servlet-name> <servlet-class>net.sx.velocity.web.MyVelocityServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>myVelocityServlet</servlet-name> <url-pattern>/myVelocityServlet</url-pattern> </servlet-mapping>