Velocity是一个基于java的模板引擎(模板引擎的作用就是取得数据并加以处理,最后显示出数据)。
它允许任何人仅仅简单的使用模板语言来引用由java代码定义的对象。
主要应用在:
应用的开发。
2.作为模板产生SQL,XML或代码等。
3.作为其他系统的集成组件使用。
当Velocity应用于application program或 a servlet,主要工作流程如下:
1.初始化Velocity.
2.创建Context对象
3.添加数据到Context
4.选择模板
5.合并模板和数据产生输出页面
准备工作:导入相关依赖包,在下面附件中。
例1:应用程序事例
1.模板文件文件
- ##这是一行注释,不会输出
- #*这是多行注释,不会输出
- 多行注释*#
- // ---------- 1.变量赋值输出------------
- Welcome $name to !
- today is $date.
- tdday is $mydae.//未被定义的变量将当成字符串
- // -----------2.设置变量值,所有变量都以$开头----------------
- #set( $iAmVariable = "good!" )
- Welcome $name to !
- today is $date.
- $iAmVariable
- //-------------,else判断--------------------------
- #set ($admin = "admin")
- #set ($user = "user")
- #if ($admin == $user)
- Welcome admin!
- #else
- Welcome user!
- #end
- //--------------4.迭代数据List---------------------
- #foreach( $product in $list )
- $product
- #end
- // ------------5.迭代数据HashSet-----------------
- #foreach($key in $() )
- $key ‘s value: $ ($key)
- #end
- //-----------6.迭代数据List Bean($velocityCount为列举序号,默认从1开始,可调整)
- #foreach ($s in $listBean)
- <$velocityCount> Address: $
- #end
- //-------------7.模板嵌套---------------------
- #foreach ($element in $list)
- #foreach ($element in $list)
- inner:This is ($velocityCount)- $element.
- #end
- outer:This is ($velocityCount)- $element.
- #end
- //-----------8.导入其它文件,多个文件用逗号隔开--------------
- #include("com/test2/")
##这是一行注释,不会输出
#*这是多行注释,不会输出
多行注释*#
// ---------- 1.变量赋值输出------------
Welcome $name to !
today is $date.
tdday is $mydae.//未被定义的变量将当成字符串
// -----------2.设置变量值,所有变量都以$开头----------------
#set( $iAmVariable = "good!" )
Welcome $name to !
today is $date.
$iAmVariable
//-------------,else判断--------------------------
#set ($admin = "admin")
#set ($user = "user")
#if ($admin == $user)
Welcome admin!
#else
Welcome user!
#end
//--------------4.迭代数据List---------------------
#foreach( $product in $list )
$product
#end
// ------------5.迭代数据HashSet-----------------
#foreach($key in $() )
$key ‘s value: $ ($key)
#end
//-----------6.迭代数据List Bean($velocityCount为列举序号,默认从1开始,可调整)
#foreach ($s in $listBean)
<$velocityCount> Address: $
#end
//-------------7.模板嵌套---------------------
#foreach ($element in $list)
#foreach ($element in $list)
inner:This is ($velocityCount)- $element.
#end
outer:This is ($velocityCount)- $element.
#end
//-----------8.导入其它文件,多个文件用逗号隔开--------------
#include("com/test2/")
2.其它非模板文件
- ==========================
- this is test's .
==========================
this is test's .
3.客户端应用测试代码:
- package com.test2;
- import ;
- import ;
- import .*;
- import ;
- import ;
- import ;
- import ;
- public class HelloVelocity {
- public static void main(String[] args) throws Exception {
- // 初始化并取得Velocity引擎
- VelocityEngine ve = new VelocityEngine();
- // 取得velocity的模版
- Properties p =new Properties();
- (Velocity.FILE_RESOURCE_LOADER_PATH, "D:/myspace/VelocityTest/src");
- (p);
- //取得velocity的模版
- Template t = ("com/test2/","utf-8");
- // 取得velocity的上下文context
- VelocityContext context = new VelocityContext();
- // 把数据填入上下文
- ("name", "Liang");
- ("date", (new Date()).toString());
- // 为后面的展示,提前输入List数值
- List temp = new ArrayList();
- ("item1");
- ("item2");
- ("list", temp);
- List tempBean = new ArrayList();
- (new UserInfo("1","张三","福建"));
- (new UserInfo("2","李四","湖南"));
- ("listBean", tempBean);
- // 输出流
- StringWriter writer = new StringWriter();
- // 转换输出
- (context, writer);
- // 输出信息
- (());
- // 输出到文件
- FileOutputStream of = new FileOutputStream("d:/");
- (().getBytes("GBK"));
- ();
- ();
- }
- }
package com.test2;
import ;
import ;
import .*;
import ;
import ;
import ;
import ;
public class HelloVelocity {
public static void main(String[] args) throws Exception {
// 初始化并取得Velocity引擎
VelocityEngine ve = new VelocityEngine();
// 取得velocity的模版
Properties p =new Properties();
(Velocity.FILE_RESOURCE_LOADER_PATH, "D:/myspace/VelocityTest/src");
(p);
//取得velocity的模版
Template t = ("com/test2/","utf-8");
// 取得velocity的上下文context
VelocityContext context = new VelocityContext();
// 把数据填入上下文
("name", "Liang");
("date", (new Date()).toString());
// 为后面的展示,提前输入List数值
List temp = new ArrayList();
("item1");
("item2");
("list", temp);
List tempBean = new ArrayList();
(new UserInfo("1","张三","福建"));
(new UserInfo("2","李四","湖南"));
("listBean", tempBean);
// 输出流
StringWriter writer = new StringWriter();
// 转换输出
(context, writer);
// 输出信息
(());
// 输出到文件
FileOutputStream of = new FileOutputStream("d:/");
(().getBytes("GBK"));
();
();
}
}
实体类
- package com.test2;
- public class UserInfo {
- private String userId;
- private String userName;
- private String address;
- public UserInfo(String userId, String userName, String address) {
- super();
- this.userId = userId;
- this.userName = userName;
- this.address = address;
- }
- public String getUserId() {
- return userId;
- }
- public void setUserId(String userId) {
- this.userId = userId;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- }
package com.test2;
public class UserInfo {
private String userId;
private String userName;
private String address;
public UserInfo(String userId, String userName, String address) {
super();
= userId;
= userName;
= address;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
= userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
= userName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
= address;
}
}
例2:Web应用事例
1.在web-inf目录下建立velocity目录,建立一模板文件。
- <html>
- <title>hello!Lizhiwo_wo!</title>
- <body>
- #set($foo = "Velocity")
- Hello $foo World! 欢迎您~~~~~~~~~~~~
- <table>
- <tr>
- <td>ID</td><td>姓名</td><td>地址</td>
- </tr>
- #foreach ($s in $listBean)
- <tr>
- <td>$</td><td>$</td><td>$</td>
- </tr>
- #end
- </table>
- </body>
- </html>
<html>
<title>hello!Lizhiwo_wo!</title>
<body>
#set($foo = "Velocity")
Hello $foo World! 欢迎您~~~~~~~~~~~~
<table>
<tr>
<td>ID</td><td>姓名</td><td>地址</td>
</tr>
#foreach ($s in $listBean)
<tr>
<td>$</td><td>$</td><td>$</td>
</tr>
#end
</table>
</body>
</html>
2.在web-inf目录下建立属性文件
- = file
- = /WEB-INF/velocity
- = true
- = 300
= file
= /WEB-INF/velocity
= true
= 300
3.建立Servlet文件
- package servlet;
- import ;
- import ;
- import ;
- import ;
- import ;
- import ;
- import ;
- import ;
- import ;
- import ;
- import ;
- import ;
- import com.;
- public class VelocityServletTest extends VelocityViewServlet{
- private static final long serialVersionUID = 1L;
- //第一步 加载配置文件这个方法会在VelocityServlet的初始化方法init()中被调用
- protected ExtendedProperties loadConfiguration(ServletConfig config) throws IOException
- {
- ExtendedProperties p = super.loadConfiguration(config);
- // 获取中配置的velocity模板路径
- String velocityLoadPath = (Velocity.FILE_RESOURCE_LOADER_PATH);
- if (velocityLoadPath != null) {
- // 获取模板路径的绝对路径
- velocityLoadPath = getServletContext().getRealPath(velocityLoadPath);
- if (velocityLoadPath != null) {
- //重新设置模板路径
- ("vMPath2:"+velocityLoadPath);
- (Velocity.FILE_RESOURCE_LOADER_PATH, velocityLoadPath);
- }
- }
- return p;
- }
- protected Template handleRequest(HttpServletRequest req,
- HttpServletResponse res,
- Context context)
- throws Exception{
- //字符编码
- ("gb2312");
- ("gb2312");
- //页面输出
- ("text/html;charset=" + "gb2312");
- List tempBean = new ArrayList();
- (new UserInfo("1","张三","福建"));
- (new UserInfo("2","李四","湖南"));
- ("listBean", tempBean);
- String templateName = "";
- // 测试信息输出
- Template t= getTemplate(templateName, "utf-8");
- StringWriter writer = new StringWriter();
- // 转换输出
- (context, writer);
- // 输出信息
- (());
- // 获取模板页面展示
- return templateName != null ? getTemplate(templateName, "utf-8") : null;
- }
- }
package servlet;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import com.;
public class VelocityServletTest extends VelocityViewServlet{
private static final long serialVersionUID = 1L;
//第一步 加载配置文件这个方法会在VelocityServlet的初始化方法init()中被调用
protected ExtendedProperties loadConfiguration(ServletConfig config) throws IOException
{
ExtendedProperties p = (config);
// 获取中配置的velocity模板路径
String velocityLoadPath = (Velocity.FILE_RESOURCE_LOADER_PATH);
if (velocityLoadPath != null) {
// 获取模板路径的绝对路径
velocityLoadPath = getServletContext().getRealPath(velocityLoadPath);
if (velocityLoadPath != null) {
//重新设置模板路径
("vMPath2:"+velocityLoadPath);
(Velocity.FILE_RESOURCE_LOADER_PATH, velocityLoadPath);
}
}
return p;
}
protected Template handleRequest(HttpServletRequest req,
HttpServletResponse res,
Context context)
throws Exception{
//字符编码
("gb2312");
("gb2312");
//页面输出
("text/html;charset=" + "gb2312");
List tempBean = new ArrayList();
(new UserInfo("1","张三","福建"));
(new UserInfo("2","李四","湖南"));
("listBean", tempBean);
String templateName = "";
// 测试信息输出
Template t= getTemplate(templateName, "utf-8");
StringWriter writer = new StringWriter();
// 转换输出
(context, writer);
// 输出信息
(());
// 获取模板页面展示
return templateName != null ? getTemplate(templateName, "utf-8") : null;
}
}
4.在文件中进行配置
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4"
- xmlns="/xml/ns/j2ee"
- xmlns:xsi="http:///2001/XMLSchema-instance"
- xsi:schemaLocation="/xml/ns/j2ee
- /xml/ns/j2ee/web-app_2_4.xsd">
- <servlet>
- <servlet-name>velocityServletTest</servlet-name>
- <servlet-class></servlet-class>
- <init-param>
- <param-name></param-name>
- <param-value>/WEB-INF/</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>velocityServletTest</servlet-name>
- <url-pattern>/velocityServletTest</url-pattern>
- </servlet-mapping>
- </web-app>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="/xml/ns/j2ee" xmlns:xsi="http:///2001/XMLSchema-instance" xsi:schemaLocation="/xml/ns/j2ee /xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>velocityServletTest</servlet-name> <servlet-class></servlet-class> <init-param> <param-name></param-name> <param-value>/WEB-INF/</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>velocityServletTest</servlet-name> <url-pattern>/velocityServletTest</url-pattern> </servlet-mapping> </web-app>
5.将其部署到tomcat下,页面访问
http://localhost:8080/VelocityTest/velocityServletTest,
输出页面如下:
- Hello Velocity World! 欢迎您~~~~~~~~~~~~
- ID 姓名 地址
- 1 张三 福建
- 2 李四 湖南
Hello Velocity World! 欢迎您~~~~~~~~~~~~
ID 姓名 地址
1 张三 福建
2 李四 湖南