velocity的基础语法

简介

velocity可以动态创建并保存静态页面,这样的话可以避免与数据库交互,实现页面的静态化,所以执行效率要比jsp高很多
其和jsp以及freemark都是作为前台的显示层其各自优缺点如下:
jsp是大家最熟悉的技术 
优点: 
1、功能强大,可以写java代码 
2、支持jsp标签(jsp tag) 
3、支持表达式语言(el) 
4、官方标准,用户群广,丰富的第三方jsp标签库 
5、性能良好。jsp编译成class文件执行,有很好的性能表现 
缺点: 
jsp没有明显缺点,非要挑点骨头那就是,由于可以编写java代码,如使用不当容易破坏mvc结构。 

velocity是较早出现的用于代替jsp的模板语言 
优点: 
1、不能编写java代码,可以实现严格的mvc分离 
2、性能良好,据说比jsp性能还要好些 
3、使用表达式语言,据说jsp的表达式语言就是学velocity的 
缺点: 
1、不是官方标准 
2、用户群体和第三方标签库没有jsp多。 
3、对jsp标签支持不够好 

freemarker 
优点: 
1、不能编写java代码,可以实现严格的mvc分离 
2、性能非常不错 
3、对jsp标签支持良好 
4、内置大量常用功能,使用非常方便 
5、宏定义(类似jsp标签)非常方便 
6、使用表达式语言 
缺点: 
1、不是官方标准 
2、用户群体和第三方标签库没有jsp多 


使用过程图

计算机生成了可选文字: Hl--rPRequest5FonVardt0VieWOntroller3.CallACtionWlthFormBeanVieWStrU污S6r甘16t幻lejspJSP幻leVmACtionVeIOcityJSSperjar毒velodty-str'Uts.jar,'n.‘…叼.--.-..一}C沪:'..-....-.…‘:卜,.'‘…。:'.k,…‘。2FillForm日ean4CreateBUSineSSoblectsMOdelFOFm日eanBusinessobjec朽6.RenderoutputHTMLXML丁XTCSV

使用velocity

try {

			Velocity.init("src/velocity.perties");//velocity的配置属性文件
			VelocityContext context = new VelocityContext();
			context.put("person", new Person());//将变量放入velocity容器
			context.put("dataTool", new DateTool());//扩展veloctiy功能,因为velocity模版可以调用对象的方法
			Template template = Velocity.getTemplate("temp.html");//读取velocity模板也可以是.vm文件
			File saveFile = new File("html/temp.html");//输出并存放静态文件
			if (!saveFile.getParentFile().exists()) {
				saveFile.getParentFile().mkdirs();
			}
			FileOutputStream outputStream = new FileOutputStream(saveFile);
			OutputStreamWriter oWriter = new OutputStreamWriter(outputStream,
					"UTF-8");
			template.merge(context, oWriter);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

velocity的属性文件

位于org.apache.velocity.runtime.default包下面的velocity.properties属性文件里
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.    

# ----------------------------------------------------------------------------
# R U N T I M E  L O G
# ----------------------------------------------------------------------------

# ----------------------------------------------------------------------------
#  default LogChute to use: default: AvalonLogChute, Log4JLogChute, CommonsLogLogChute, ServletLogChute, JdkLogChute
# ----------------------------------------------------------------------------

runtime.log.logsystem.class = org.apache.velocity.runtime.log.AvalonLogChute,org.apache.velocity.runtime.log.Log4JLogChute,org.apache.velocity.runtime.log.CommonsLogLogChute,org.apache.velocity.runtime.log.ServletLogChute,org.apache.velocity.runtime.log.JdkLogChute

# ---------------------------------------------------------------------------
# This is the location of the Velocity Runtime log.
# ----------------------------------------------------------------------------

runtime.log = velocity.log

# ----------------------------------------------------------------------------
# This controls whether invalid references are logged.
# ----------------------------------------------------------------------------

runtime.log.invalid.references = true

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

input.encoding=ISO-8859-1
output.encoding=ISO-8859-1

# ----------------------------------------------------------------------------
# F O R E A C H  P R O P E R T I E S
# ----------------------------------------------------------------------------
# These properties control how the counter is accessed in the #foreach
# directive. By default the reference $velocityCount and $velocityHasNext
# will be available in the body of the #foreach directive.
# The default starting value for $velocityCount is 1.
# ----------------------------------------------------------------------------

directive.foreach.counter.name = velocityCount
directive.foreach.counter.initial.value = 1
directive.foreach.maxloops = -1

directive.foreach.iterator.name = velocityHasNext

# ----------------------------------------------------------------------------
# S E T  P R O P E R T I E S
# ----------------------------------------------------------------------------
# These properties control the behavior of #set.
# For compatibility, the default behavior is to disallow setting a reference
# to null.  This default may be changed in a future version.
# ----------------------------------------------------------------------------

directive.set.null.allowed = false

# ----------------------------------------------------------------------------
# I F  P R O P E R T I E S
# ----------------------------------------------------------------------------
# These properties control the behavior of #if
# Default behavior is to check return value of toString() and treat an object
# with toString() that returns null as null. If all objects have toString()
# methods that never return null, this check is unnecessary and can be disabled
# to gain performance. In Velocity 1.5, no such null check was performed.
directive.if.tostring.nullcheck = true

# ----------------------------------------------------------------------------
# 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.parse.max.depth = 10

# ----------------------------------------------------------------------------
# S C O P E  P R O P E R T I E S
# ----------------------------------------------------------------------------
# These are the properties that govern whether or not a Scope object
# is automatically provided for each of the given scopes to serve as a
# scope-safe reference namespace and "label" for #break calls. The default
# for most of these is false.  Note that <bodymacroname> should be replaced by
# name of macros that take bodies for which you want to suppress the scope.
# ----------------------------------------------------------------------------
# template.provide.scope.control = false
# evaluate.provide.scope.control = false
foreach.provide.scope.control = true
# macro.provide.scope.control = false
# define.provide.scope.control = false
# <bodymacroname>.provide.scope.control = false

# ----------------------------------------------------------------------------
# T E M P L A T E  L O A D E R S
# ----------------------------------------------------------------------------
#
#
# ----------------------------------------------------------------------------

resource.loader = file

file.resource.loader.description = Velocity File Resource Loader
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = .
file.resource.loader.cache = false
file.resource.loader.modificationCheckInterval = 2

string.resource.loader.description = Velocity String Resource Loader
string.resource.loader.class = org.apache.velocity.runtime.resource.loader.StringResourceLoader

# ----------------------------------------------------------------------------
# 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.
# ----------------------------------------------------------------------------
# velocimacro.library = VM_global_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.max.depth = 20

# ----------------------------------------------------------------------------
# VELOCIMACRO STRICT MODE
# ----------------------------------------------------------------------------
# if true, will throw an exception for incorrect number 
# of arguments.  false by default (for backwards compatibility)
# but this option will eventually be removed and will always
# act as if true
# ----------------------------------------------------------------------------
velocimacro.arguments.strict = false

# ----------------------------------------------------------------------------
# VELOCIMACRO BODY REFERENCE 
# ----------------------------------------------------------------------------
# Defines name of the reference that can be used to render the AST block passed to
# block macro call as an argument inside a macro.
# ----------------------------------------------------------------------------
velocimacro.body.reference=bodyContent

# ----------------------------------------------------------------------------
# STRICT REFERENCE MODE
# ----------------------------------------------------------------------------
# if true, will throw a MethodInvocationException for references
# that are not defined in the context, or have not been defined
# with a #set directive. This setting will also throw an exception
# if an attempt is made to call a non-existing property on an object
# or if the object is null.  When this property is true then property
# 'directive.set.null.allowed' is also set to true.
# ----------------------------------------------------------------------------
runtime.references.strict = 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.manager.class = org.apache.velocity.runtime.resource.ResourceManagerImpl
resource.manager.cache.class = org.apache.velocity.runtime.resource.ResourceCacheImpl

# ----------------------------------------------------------------------------
# PARSER POOL
# ----------------------------------------------------------------------------
# Selects a custom factory class for the parser pool.  Must implement
# ParserPool.  parser.pool.size is used by the default implementation
# ParserPoolImpl
# ----------------------------------------------------------------------------

parser.pool.class = org.apache.velocity.runtime.ParserPoolImpl
parser.pool.size = 20


# ----------------------------------------------------------------------------
# EVENT HANDLER
# ----------------------------------------------------------------------------
# Allows alternative event handlers to be plugged in.  Note that each
# class property is actually a comma-separated list of classes (which will
# be called in order).
# ----------------------------------------------------------------------------
# eventhandler.referenceinsertion.class =
# eventhandler.nullset.class =
# eventhandler.methodexception.class =
# eventhandler.include.class =


# ----------------------------------------------------------------------------
# EVALUATE
# ----------------------------------------------------------------------------
# Evaluate VTL dynamically in template.  Select a class for the Context, if
# you want all #set calls within it to be locally scoped.  This feature is
# deprecated; please use $evaluate to hold local references instead.
# ----------------------------------------------------------------------------

#directive.evaluate.context.class = org.apache.velocity.VelocityContext


# ----------------------------------------------------------------------------
# PLUGGABLE INTROSPECTOR
# ----------------------------------------------------------------------------
# Allows alternative introspection and all that can of worms brings.
# ----------------------------------------------------------------------------

runtime.introspector.uberspect = org.apache.velocity.util.introspection.UberspectImpl


# ----------------------------------------------------------------------------
# SECURE INTROSPECTOR
# ----------------------------------------------------------------------------
# If selected, prohibits methods in certain classes and packages from being 
# accessed.
# ----------------------------------------------------------------------------

introspector.restrict.packages = java.lang.reflect

# The two most dangerous classes

introspector.restrict.classes = java.lang.Class
introspector.restrict.classes = java.lang.ClassLoader
                
# Restrict these for extra safety

introspector.restrict.classes = java.lang.Compiler
introspector.restrict.classes = java.lang.InheritableThreadLocal
introspector.restrict.classes = java.lang.Package
introspector.restrict.classes = java.lang.Process
introspector.restrict.classes = java.lang.Runtime
introspector.restrict.classes = java.lang.RuntimePermission
introspector.restrict.classes = java.lang.SecurityManager
introspector.restrict.classes = java.lang.System
introspector.restrict.classes = java.lang.Thread
introspector.restrict.classes = java.lang.ThreadGroup
introspector.restrict.classes = java.lang.ThreadLocal



语法demo

<html>
 
<body>
 
##1. 单行注释
 
#*2. 多行注释
 
多行注释*#
 
##3. 变量赋值
 
#set($var="Velocity")
 
##4. 变量 第一个字符必须为字母
 
<p> 4.The var is: $var</p>
 
##5.字符串拼接
 
#set ( $size="Big" )
 
#set ( $name="Ben" )
 
#set ( $clock="$size$name")
 
<p>5.字符串拼接: $clock </p>
 
##6. 单双引号
 
<p> 6. 双引号时: </p>
 
#set ( $clock="$size$name")
 
$clock
 
<p> 单引号时: </p>
 
#set ($clock='$size$name')
 
$clock
 
##7. {}
 
<p>7. 没用{}:this is a $varfile.</p>
 
<p>用{}: this is a ${var}file.</p>
 
##8. ! ?
 
#set($var=$null)
 
<p>8. 没用!: $null</p>
 
<p> 用!: $!null </p>
 
##9. \ 转义
 
#set( $var = "Velocity" )
 
<p>9. \$var变为: $var
 
<p>\\\$var变为: \$var
 
<p>\\\\\$var变为: \\$var
 
<p>\\\\\\\$var变为: \\\$var
 
##10. if else
 
<p>10. if else例子:</p>
 
#if( $var )
 
<strong>run if!</strong>
 
#else
 
<strong>run else!</strong>
 
#end
 
#*11. #set( LHS = RHS )
 
LHS可以是变量引用或属性引用
 
RHS可以是引用、字符串、数字、ArrayList或Map *#
 
##set($var.list=["Not", "wrong", "fault"])
 
##set($var.Map=["banana": "good", "roast beef":"bad"])
 
##12. #foreach
 
##arraylist table...
 
<p>12. foreach列表:</p>
 
#set($criteria=["java", "c", "php"])
 
#foreach($lang in $criteria)
 
$velocityCount
 
$lang
 
#end
 
## num scope
 
<p>数字范围:</p>
 
#foreach( $num in [1..5] )
 
$num
 
#end
 
##13. #macro宏命令
 
<p>13. macro 无参数:</p>
 
#macro( macroo )
 
<tr><td bgcolor=red>$var</td></tr>
 
#end
 
##调用
 
<table>
 
#macroo()
 
#macroo()
 
</table>
 
<p>13. macro 有参数:
 
##参数为:$color 和$somelist
 
#macro( macroname $color $somelist )
 
#foreach( $something in $somelist )
 
<tr><td bgcolor=$color>$something</td></tr>
 
#end
 
#end
 
##调用
 
#set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )
 
#set( $color = "blue" )
 
<table>
 
#macroname( $color $greatlakes ) ##调用模板tablerows
 
</table>
 
<p>13. macro嵌套 参数以by name形式传递
 
##声明
 
#macro( inner $foo )
 
inner : $foo
 
#end
 
#macro( outer $foo )
 
#set($bar = "outerlala")
 
outer : $foo
 
#end
 
##调用
 
#set($bar = 'calltimelala')
 
#outer( "#inner($bar)" )
 
## include 导入的文件内容不会被模板引擎解析。
 
## parse 许导入一个包含VTL的本地文件,并由模板引擎进行解析。
 
## #stop 停止模板引擎的执行并返回。这在Debug时很有用。
 
</body>
 
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值