velociy模板引擎使用詳解

1.velocity簡介
Velocity  是一個基於 Java 的模版引擎。它允許 web  頁面設計者引用 JAVA 代碼預定義的方法。 Web  設計者可以根據 MVC 模式和 JAVA 程序員並行工作,這意味着 Web 設計者可以單獨專注於設計良好的站點,而程序員則可單獨專注於編寫底層代碼。 Velocity  將 Java  代碼從 web 頁面中分離出來,使站點在長時間運行後仍然具有很好的可維護性,並提供了一個除 JSP 和 PHP 之外的可行的被選方案。

2.使用方法
(1)velocity是apache的開源項目,下載地址http://velocity.apache.org/
(2)新建項目工程文件vtl,目錄結構如下,同時在web-inf下新建conf,layout,www目錄


(3)導入相關jar包

(4)在web-inf/conf目錄新建velocity.properties

#----------------------------------------------------------------------------
# These are the default properties for the
# Velocity Runtime. These values are used when
# Runtime.init() is called, and when Runtime.init(properties)
# fails to find the specificed properties file.
#----------------------------------------------------------------------------

parser.pool.size=200


#----------------------------------------------------------------------------
# R U N T I M E  L O G
#----------------------------------------------------------------------------
# Velocity uses the Servlet APIs logging facilites.

#----------------------------------------------------------------------------
# This controls if Runtime.error(), info() and warn() messages include the
# whole stack trace. The last property controls whether invalid references
# are logged.
#----------------------------------------------------------------------------
#runtime.log.logsystem = 
#runtime.log.logsystem.class = 
runtime.log.error.stacktrace = true
runtime.log.warn.stacktrace  = true
runtime.log.info.stacktrace  = false
runtime.log.debug.stacktrace = false
runtime.log.invalid.references = false

#----------------------------------------------------------------------------
# T E M P L A T E  E N C O D I N G
#----------------------------------------------------------------------------

default.contentType=text/html

input.encoding=UTF-8
output.encoding=UTF-8

#----------------------------------------------------------------------------
# I N C L U D E  P R O P E R T I E S
#----------------------------------------------------------------------------
# These are the properties that governed the way #include'd content
# is governed.
#----------------------------------------------------------------------------

directive.include.output.errormsg.start = <!-- include error :
directive.include.output.errormsg.end   =  see error log -->


#----------------------------------------------------------------------------
# P A R S E  P R O P E R T I E S
#----------------------------------------------------------------------------
directive.set.null.allowed = true
directive.parse.max.depth = 10

#----------------------------------------------------------------------------
# VELOCIMACRO PROPERTIES
#----------------------------------------------------------------------------
# global : name of default global library.  It is expected to be in the regular
# template path.  You may remove it (either the file or this property) if
# you wish with no harm.
#----------------------------------------------------------------------------
#dev-changes by Marino

velocimacro.library.autoreload = true
velocimacro.library = /WEB-INF/conf/VM_common_library.vm

velocimacro.permissions.allow.inline = true
velocimacro.permissions.allow.inline.to.replace.global = false
velocimacro.permissions.allow.inline.local.scope = false

velocimacro.context.localscope = false

velocimacro.messages.on = false

#----------------------------------------------------------------------------
# INTERPOLATION
#----------------------------------------------------------------------------
# turn off and on interpolation of references and directives in string
# literals.  ON by default :)
#----------------------------------------------------------------------------
runtime.interpolate.string.literals = true

#----------------------------------------------------------------------------
# RESOURCE MANAGEMENT
#----------------------------------------------------------------------------
# Allows alternative ResourceManager and ResourceCache implementations
# to be plugged in.
#----------------------------------------------------------------------------

resource.loader = webapp

# webapp.resource.loader.description = Velocity File Resource Loader
# webapp.resource.loader.class = org.apache.velocity.tools.view.servlet.WebappLoader
# webapp.resource.loader.path = /
# webapp.resource.loader.cache = false
# webapp.resource.loader.modificationCheckInterval = 600

# resource.manager.class = org.apache.velocity.runtime.resource.ResourceManagerImpl
# resource.manager.cache.class = org.apache.velocity.runtime.resource.ResourceCacheImpl
resource.manager.logwhenfound = false

#----------------------------------------------------------------------------
# VelocityLayoutServlet
#----------------------------------------------------------------------------
# Filepath for error template, 
#  relative to web application root directory
#  處理錯誤信息的模板路徑
tools.view.servlet.error.template = /WEB-INF/www/500.vm

# Directory for layout templates, 
#  relative to web application root directory
#  所有佈局文件的默認路徑
tools.view.servlet.layout.directory = /WEB-INF/layout

# Filepath of the default layout template 
#  relative to the layout directory 
#  NOT relative to the root directory of the webapp!
#  默認的佈局文件
tools.view.servlet.layout.default.template =  default.vm

說明:

①/WEB-INF/conf/VM_common_library.vm是宏文件的路徑,下面我們會創建
②tools.view.servlet.layout.directory = /WEB-INF/layout是佈局模板路徑
③tools.view.servlet.layout.default.template =  default.vm是默認的佈局文件,下面我們會創建
(4)新建類文件

package com.foxhu.sims.velocity;
public class SIMS_VelocityTool {
	public String data() {
		return "data from Tool";
	}
}
該類主要給頁面模板提供數據
(6)在web-inf/conf目錄新建velocity-toolbox.xml
<?xml version="1.0" encoding="UTF-8"?>
<toolbox>
	<tool>
		<key>sims</key>
		<scope>request</scope>
		<class>com.foxhu.sims.velocity.SIMS_VelocityTool</class>
	</tool>
	<tool>
		<key>escape</key>
		<scope>application</scope>
		<class>org.apache.velocity.tools.generic.EscapeTool</class>
	</tool>
	<tool>
	    <key>date</key>
	    <scope>application</scope>
	    <class>org.apache.velocity.tools.generic.DateTool</class>
  </tool>
</toolbox>

說明:該文件主要是給模板文件提供數據,例如引用SIMS_VelocityTool類中的數據(裏面有個data()方法)那麼在模板中可以$sims.data()引用
(7)在web-inf/conf目錄新建VM_common_library.vm文件,該文件爲宏文件,主要定義一些全局用到的宏,例如顯示信息和生成翻頁鏈接的宏
#macro(show_msg_box $__msg)
<div class="msgbox">
	${__msg}<br/><br/><a href="#" οnclick="history.go(-1);return false;">返回上頁</a>
</div>
<div class="spacer_1"></div>
#end

#*
 * 生成翻頁鏈接
 * 作者: Winter Lau
 *#
#macro(pager $__uri $__obj_count $__page_size)
#if($__obj_count > $__page_size)
    #if($__uri.indexOf("?")>=0)#set($param_char='&')#else#set($param_char='?')#end
    #if(!$__uri.endsWith("?") && !$__uri.endsWith("&"))
		#set($__p_uri = "${__uri}${param_char}")
	#else
		#set($__p_uri = $__uri)
	#end
    #set($PAGE_COUNT = $osc_tool.page_count($__obj_count, $__page_size))
    #set($__p = $link.param("p",1))
	#if($__p <= $PAGE_COUNT)
    #set($pre_page = $__p - 1)
    #set($next_page = $__p + 1)
	#if($__p > 3)
    	#set($begin_idx = $__p - 3)
	#else
		#set($begin_idx = 1)
	#end	
    #set($end_idx = $begin_idx + 9)
    #if($end_idx > $PAGE_COUNT)#set($end_idx = $PAGE_COUNT)#end
    <ul class="pager">
        #if($__p > 1)<li class='page prev'><a href="${__p_uri}p=$pre_page"><</a></li>#end#if($begin_idx > 1)<li class='page'><a href="${__p_uri}">1</a></li>#end#foreach($idx in [$begin_idx..$end_idx])#if($idx != $__p)<li class='page'><a href="${__p_uri}p=$idx">$idx</a></li>#else<li class='page current'><a href="${__p_uri}p=$idx">$idx</a></li>#end#end#if($end_idx < $PAGE_COUNT)<li class='page'><a href="${__p_uri}p=$PAGE_COUNT">$PAGE_COUNT</a></li>#end#if($__p < $PAGE_COUNT)<li class='page next'><a href="${__p_uri}p=$next_page">></a></li>#end
    </ul>
	#end
#end
#end
(8)在web-inf/layout目錄新建default.vm默認佈局文件
<html >
<head >
	<title>$!page_title</title>
</head>
<body>
##$screen_content便是VelocityLayoutServlet保留的關鍵字,Velocity依此關鍵字來潛入實際被 引用的頁面內容
	$screen_content
</body>
</html>
(9)在web-inf/www目錄新建錯誤頁面模板500.vm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>ERROR</title>
    <style type="text/css">
    <!--
        body {font-family: arial,sans-serif}
		#error{padding:20px}
		#title_bar{background-color:#dd0000;padding:8px;padding-left:20px;font-size:16pt;font-weight:bold;color:#ffff00}
		#info{padding-top:20px;padding-bottom:20px;color:#0000aa}
        #error_detail{padding:2px;background-color:#eeeeee;}
		#error_time{padding:2px;font-size:8pt}
    //-->
    </style>
</head>

<body>
<div id="error">
  <div id="title_bar">$escape.html("!!! 錯 誤 !!!")</div>
    <div id="info">
      <h2>$escape.html("您訪問的頁面發生錯誤!")</h2>
		$escape.html("請將此錯誤信息報告給我們的系統管理員,以便我們儘快爲您解決該問題。")<br/><br/>        
		$escape.html("您可以通過電子郵件:")<a href="mailto:[email protected]">[email protected]</a> $escape.html("將下面的信息發送給我們。")<br/><br/>
	    $escape.html("感謝您對我們的大力支持!")(<a href="#" οnclick="history.go(-1);return false;">$escape.html("回到上頁")</a>)
    </div>
	
	<div id="error_time">$date.get("yyyy-MM-dd HH:mm:ss")</div>
</div>
</body>
</html>
(10)修改xml文件的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>vtl</display-name>
  <servlet>
    <servlet-name>velocity</servlet-name>
    <servlet-class>org.apache.velocity.tools.view.servlet.VelocityLayoutServlet</servlet-class>
    <init-param>
			<param-name>org.apache.velocity.toolbox</param-name>
			<param-value>/WEB-INF/conf/velocity-toolbox.xml</param-value>
	</init-param>
	<init-param>
		<param-name>org.apache.velocity.properties</param-name>
		<param-value>/WEB-INF/conf/velocity.properties</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>velocity</servlet-name>
    <url-pattern>*.vm</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
		<welcome-file>index.vm</welcome-file>
	</welcome-file-list>
	<error-page>
		<error-code>404</error-code>
		<location>/404.vm</location>
	</error-page>
	<error-page>
		<error-code>500</error-code>
		<location>/500.vm</location>
	</error-page>
</web-app>
(111)新建測試頁面test.vm
#set($page_title="Layout Test")
Hello Velocity Layout!
$sims.data();
說明:這裏不需要寫html,head和body標籤,因爲我們在default.vm模板已經配置過了,這就是velocity的layout的經典應用
(12)啓動tomcat,在地址欄輸入http://localhost:8080/vtl/test.vm,會看到如下結果
Hello Velocity Layout! data from Tool;
(13)完整的項目目錄結構如下


參考資料:
http://www.oschina.net/question/12_4580
http://www.oschina.net/code/snippet_12_5638








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章