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:foxhu.cn@gmail.com">foxhu.cn@gmail.com</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








  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值