首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

Velocity模板使用

2012-09-02 
Velocity模板应用Velocity是一个基于java的模板引擎(模板引擎的作用就是取得数据并加以处理,最后显示出数

Velocity模板应用

Velocity是一个基于java的模板引擎(模板引擎的作用就是取得数据并加以处理,最后显示出数据)。
???? 它允许任何人仅仅简单的使用模板语言来引用由java代码定义的对象。
????
主要应用在:
??1.Web应用的开发。
??2.作为模板产生SQL,XML或代码等。
??3.作为其他系统的集成组件使用。

?

当Velocity应用于application program或 a servlet,主要工作流程如下:
??1.初始化Velocity.
??2.创建Context对象
??3.添加数据到Context
??4.选择模板
??5.合并模板和数据产生输出页面

?

准备工作:导入相关依赖包,在下面附件中。

?

例1:应用程序事例

?

1.模板文件hellovelocity.vm文件

##这是一行注释,不会输出#*这是多行注释,不会输出   多行注释*#// ---------- 1.变量赋值输出------------Welcome $name to Javayou.com!today is $date.tdday is $mydae.//未被定义的变量将当成字符串// -----------2.设置变量值,所有变量都以$开头----------------#set( $iAmVariable = "good!" )Welcome $name to Javayou.com!today is $date.$iAmVariable//-------------3.if,else判断--------------------------#set ($admin = "admin")#set ($user = "user")#if ($admin == $user)Welcome admin!#elseWelcome user!#end//--------------4.迭代数据List---------------------#foreach( $product in $list )$product#end// ------------5.迭代数据HashSet-----------------#foreach($key in $hashVariable.keySet() )  $key ‘s value: $ hashVariable.get($key)#end//-----------6.迭代数据List Bean($velocityCount为列举序号,默认从1开始,可调整)#foreach ($s in $listBean)<$velocityCount> Address: $s.address#end//-------------7.模板嵌套---------------------#foreach ($element in $list)#foreach ($element in $list)inner:This is ($velocityCount)- $element.#endouter:This is ($velocityCount)- $element.#end//-----------8.导入其它文件,多个文件用逗号隔开--------------#include("com/test2/test.txt")

?

2.其它非模板文件text.txt

   ======text.txt====================   this is test's content.yeah.

?

3.客户端应用测试代码:

package com.test2;import java.io.FileOutputStream;import java.io.StringWriter;import java.util.*;import org.apache.velocity.app.Velocity;import org.apache.velocity.app.VelocityEngine;import org.apache.velocity.Template;import org.apache.velocity.VelocityContext;public class HelloVelocity {public static void main(String[] args) throws Exception {// 初始化并取得Velocity引擎VelocityEngine ve = new VelocityEngine();// 取得velocity的模版Properties p =new Properties();p.put(Velocity.FILE_RESOURCE_LOADER_PATH, "D:/myspace/VelocityTest/src");ve.init(p);//取得velocity的模版 Template t = ve.getTemplate("com/test2/hellovelocity.vm","utf-8"); // 取得velocity的上下文contextVelocityContext context = new VelocityContext();// 把数据填入上下文context.put("name", "Liang");context.put("date", (new Date()).toString());// 为后面的展示,提前输入List数值List temp = new ArrayList();temp.add("item1");temp.add("item2");context.put("list", temp);List tempBean = new ArrayList();tempBean.add(new UserInfo("1","张三","福建"));tempBean.add(new UserInfo("2","李四","湖南"));context.put("listBean", tempBean);// 输出流StringWriter writer = new StringWriter();// 转换输出t.merge(context, writer);// 输出信息System.out.println(writer.toString());// 输出到文件FileOutputStream of = new FileOutputStream("d:/velocity.txt");                           of.write(writer.toString().getBytes("GBK"));                            of.flush();                           of.close();}}

?

4.UserInfo实体类

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;}}

?

例2:Web应用事例

?

1.在web-inf目录下建立velocity目录,建立一模板文件velocity.vm。

<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>$s.userId</td><td>$s.userName</td><td>$s.address</td></tr>#end</table></body></html>

?

2.在web-inf目录下建立velocity.properties属性文件

resource.loader = filefile.resource.loader.path = /WEB-INF/velocityfile.resource.loader.cache = truefile.resource.loader.modificationCheckInterval = 300

?

3.建立Servlet文件VelocityServletTest.java

package servlet;import java.io.IOException;import java.io.StringWriter;import java.util.ArrayList;import java.util.List;import javax.servlet.ServletConfig;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.collections.ExtendedProperties;import org.apache.velocity.Template;import org.apache.velocity.app.Velocity;import org.apache.velocity.context.Context;import org.apache.velocity.tools.view.servlet.VelocityViewServlet;import com.test2.UserInfo;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.properties中配置的velocity模板路径        String velocityLoadPath = p.getString(Velocity.FILE_RESOURCE_LOADER_PATH);                   if (velocityLoadPath != null) {                // 获取模板路径的绝对路径        velocityLoadPath = getServletContext().getRealPath(velocityLoadPath);            if (velocityLoadPath != null) {            //重新设置模板路径             System.out.println("vMPath2:"+velocityLoadPath);                p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, velocityLoadPath);                           }        }        return p;    }protected Template handleRequest(HttpServletRequest req,  HttpServletResponse res,  Context context) throws Exception{//字符编码    req.setCharacterEncoding("gb2312");        res.setCharacterEncoding("gb2312");        //页面输出        res.setContentType("text/html;charset=" + "gb2312");List tempBean = new ArrayList();tempBean.add(new UserInfo("1","张三","福建"));tempBean.add(new UserInfo("2","李四","湖南"));context.put("listBean", tempBean);    String templateName = "velocity.vm";        // 测试信息输出    Template t= getTemplate(templateName, "utf-8");    StringWriter writer = new StringWriter();// 转换输出t.merge(context, writer);// 输出信息System.out.println(writer.toString());        // 获取模板页面展示            return templateName != null ? getTemplate(templateName, "utf-8") : null;}}

?

?4.在web.xml文件中进行配置

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"><servlet>        <servlet-name>velocityServletTest</servlet-name>        <servlet-class>servlet.VelocityServletTest</servlet-class>        <init-param>            <param-name>org.apache.velocity.properties</param-name>            <param-value>/WEB-INF/velocity.properties</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李四湖南

?

热点排行