`

Velocity java开发指南》中文版(下)

阅读更多
[size=medium]8.Application Attributes
Application Attributes (应用程序属性)是和VelocityEngine 的运行时实例(Runtimeinstance)相关联的,名-值对(name-value pairs)格式的参数,可用来存运RuntimeInstance时的信息.
设计这个功能的目标是Velocity程序需要与应用层或用户定制部分(如日志,资源,装载器等)通信.
The Application Attribute API is very simple. From the application layer,在 VelocityEngine 和 Velocity classes 中都有如下命令:
public void setApplicationAttribute( Object key, Object value );
这里的key与value的设置没有任何限制,可以在程序运行中设置,这是不同与Velocity的init()调用的.
内部程序可以通过接口 RuntimeServices 如下的命令来取得这些参数:
public Object getApplicationAttribute( Object key ):
9.EventCartridge and Event Handlers(事件分发和处理)
1.Event Handlers
从Velocity1.1版本起,加入了良好的事件处理机制. 你可将自己的事件处理器类注册给事件分发器(EventCartridge) , 事件分发器实际上扮演着Velocity engine在运行时访问事件处理器(event handlers)的一个代理的角色。目前,有3种Velocity系统定义的事件可以被处理,它们都位与包org.apache.velocity.app.event 中.
org.apache.velocity.app.event.NullSetEventHandler
当模板中#set() 指令关联的是一个空值时, 这是很常见的一个问题. The NullSetEventHandler 事件处理器可以让你决定如何处理,其接口代码如下.
public interface NullSetEventHandler extends EventHandler
{
    public boolean shouldLogOnNullSet( String lhs, String rhs );
}

org.apache.velocity.app.event.ReferenceInsertionEventHandler

A ReferenceInsertionEventHandler 这个事件处理器可以让开发者在引用对象值如($foo)输出到模板之前截取修改.
public interface ReferenceInsertionEventHandler extends EventHandler
{
    public Object referenceInsert( String reference, Object value );
}
org.apache.velocity.app.event.MethodExceptionEventHandler

当用户数据对象中的某个命令出错时, 实现了 MethodExceptionEventHandler接口的事件处理器将被调用以获得具体的命令名字和Exception对象. 事件处理器也可以重组一个有效的对象返回(一般用于统一的异常处理), 或向它的父类throws一个new Exception, MethodInvocationException接口如下:
public interface MethodExceptionEventHandler extends EventHandler
{
    public Object methodException( Class claz, String method, Exception e )
         throws Exception;
}
2.Using the EventCartridge使用事件分发器
可以直接使用一个事件分发器(EventCartridge),如下例程在org.apache.velocity.test.misc.Test中:
...

import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
import org.apache.velocity.app.event.MethodExceptionEventHandler;
import org.apache.velocity.app.event.NullSetEventHandler;

...

public class Test implements ReferenceInsertionEventHandler,
                             NullSetEventHandler,
                             MethodExceptionEventHandler
{
    public void myTest()
    {
        ....

        /*
         * now, it's assumed that Test implements the correct methods to
         * support the event handler interfaces. So to use them, first
         * make a new cartridge
         */
        EventCartridge ec = new EventCartridge();

        /*
         * then register this class as it contains the handlers
         */
        ec.addEventHandler(this);

        /*
         * and then finally let it attach itself to the context
         */
        ec.attachToContext( context );

        /*
         * now merge your template with the context as you normally
         * do
         */

        ....
    }

    /*
     * and now the implementations of the event handlers
     */
    public Object referenceInsert( String reference, Object value )
    {
        /* do something with it */
        return value;
    }

    public boolean shouldLogOnNullSet( String lhs, String rhs )
    {
        if ( /* whatever rule */ )
            return false;

        return true;
    }

    public Object methodException( Class claz, String method, Exception e )
         throws Exception
    {
        if ( /* whatever rule */ )
           return "I should have thrown";

        throw e;
    }
}

10.Velocity Configuration Keys and Values(配置参数名字和值说明)
Velocity's runtime configuration is controlled by a set of configuration keys listed below Velocity的运行时配置由一个key-value列表控制.
Velocity中有一些默认的值在以下位置可以找到:
/src/java/org/apache/velocity/runtime/defaults/velocity.defaults,Velocity基础配置,它会确保Velocity总是有一个“正常的”配置以便运行.但它不一定是你想要的配置.
任何配置必须在 init()调用前发生才会在运行时替换掉默认的配置。这意味着你只需改变你需要的而不是所有的配置都要动.
这一节: Using Velocity In General Applications 有关于configuration API的进一步说明.
以下,是默认配置的说明:
1.Runtime Log
runtime.log = velocity.log
用以指定Velocity运行时日志文件的路劲和日志文件名,如不是全限定的绝对路径,系统会认为想对于当前目录.
runtime.log.logsystem
这个参数没有默认值,它可指定一个实现了interface org.apache.velocity.runtime.log.LogSystem.的自定义日志处理对象给Velocity。这就方便将Velocity与你己有系统的日志机制统一起来.具体可见Configuring the Log System 这一节.
runtime.log.logsystem.class = org.apache.velocity.runtime.log.AvalonLogSystem
上面这行,是一个示例来指定一个日志记录器.
runtime.log.error.stacktrace = false
runtime.log.warn.stacktrace = false
runtime.log.info.stacktrace = false
这些是错误消息跟踪的开关.将会生成大量、详细的日志内容输出.
runtime.log.invalid.references = true
当一个引用无效时,打开日志输出. 在生产系统运行中,这很有效,也是很有用的调试工具.
2.字符集编码问题
input.encoding = ISO-8859-1
输出模板的编码方式 (templates). 你可选择对你模板的编码方式,如UTF-8.GBK.
output.encoding = ISO-8859-1
VelocityServlet 对输出流(output streams)的编码方式.
3.#foreach() Directive
directive.foreach.counter.name = velocityCount
在模板中使用#foreach() 指令时,这里设定的字符串名字将做为context key 代表循环中的计数器名,如以上设定,在模板中可以通过 $velocityCount来访问.
directive.foreach.counter.initial.value = 1
#foreach() 中计数器的起始值.
4.#include() and #parse() Directive
directive.include.output.errormsg.start =
directive.include.output.errormsg.end =
使用#include()时,定义内部流中开始和结束的错误消息标记,如果两者都设这屯,错误消息将被输出到流中'.但必须是两都定义.
directive.parse.maxdepth = 10
定义模板的解析深度,当在一个模板中用#parse()指示解析另外一个模板时,这个值可以防止解析时出现recursion解析.
5.资源管理
resource.manager.logwhenfound = true
定义日志中的 'found' 务目开关.当打开时,如Resource Manager第一次发现某个资源时, the first time, the resource name and classname of the loader that found it will be noted in the runtime log.
resource.loader = <name> (default = File)
Multi-valued key. Will accept CSV for value. (可以有多个以.号分开的值),可以理解为指定资源文件的扩展名.
<name>.loader.description = Velocity File Resource Loader
描述资源装载器名字.
<name>.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
实现的资源装载器的类名. 默认的是文件装载器.
<name>.resource.loader.path = .
Multi-valued key. Will accept CSV for value. 资源位置的根目录. 当前配置会使用FileResourceLoader and JarResourceLoader 遍历目录下的所有文件以查找资源.
<name>.resource.loader.cache = false
控制装载器是否对文件进行缓存.默认不存是为了方便开发和调试. 在生产环境布署(production deployment)时可设为true以提高性能, 这里参数 modificationCheckInterval应设为一个有效值—以决定多久reload一次.
<name>.resource.loader.modificationCheckInterval = 2
当模把caching打开时,这个以秒为单位的值指示系统多久检测一次模板是否己修改以决定是否需要,如果设为 <= 0, Velocity将不做检测.
FileResourceLoader 的默认参数完整示例:
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

6.Velocimacro(宏配置)
velocimacro.library = VM_global_library.vm
Multi-valued key. Will accept CSV for value.当Velocity engine运行时,要被载入的含有宏代码库的文件名. 所有模板都可访问宏(Velocimacros ). 这个文件位置在相对于资源文件的根目录下.
velocimacro.permissions.allow.inline = true
Determines of the definition of new Velocimacros via the #macro() directive in templates is allowed,定义在模板中是否可用#macro()指令定义一个新的宏. 默认为true,意味所有模板都可定义new Velocimacros. 注意,这个设定,如模板中的有可能替换掉全局的宏定义.
velocimacro.permissions.allow.inline.to.replace.global = false
控制用户定义的宏是否可以可以替换Velocity的宏库.
velocimacro.permissions.allow.inline.local.scope = false
控制模板中的宏的专有命名空间.When true, 一个模板中的 #macro() directive 只能被定义它的模板访问. 这意味者所有的宏都不能共想了,当然也不会互想扰乱、替换了.
velocimacro.context.localscope = false控制Velocimacro 的引用访问(set/get)是涉及到Context范围还是仅在当前的Velocimacro中.
velocimacro.library.autoreload = false
控制宏库是否自动载入. 设为true时,源始的Velocimacro 将根据是否修改过而决定是否需要reLoad,可在调试时很方便,不需重启你的服务器,如用参数 file.resource.loader.cache = false的设置一样,主要是为方便开发调试用.
7.语义更改
runtime.interpolate.string.literals = true
Controls interpolation mechanism of VTL String Literals. Note that a VTL StringLiteral is specifically a string using double quotes that is used in a #set() statement, a method call of a reference, a parameter to a VM, or as an argument to a VTL directive in general. See the VTL reference for further information.
8.运行时配置
parser.pool.size = 20
控制Velocity启动是需要创建并放到池中预备使用的模板解析器的个数----这只是预装. 默认的20个对一般用户来说足够了. 即使这个值小了,Velocity也会运行时根据系统需要动态增加(但增加的不会装入池中). 新增时会在日志中输出信息

11.Configuring the Log System(日志记录配置)
Velocity有很容易扩展的日志系统.即使不做任何设置,velocity也会将日志输出到当前目录下的 velocity.log文件中. 对一些高级用户, 可以很方便的将你当前系统的日志和它整合起来.
从1.3开始, Velocity 默认使用 Jakarta Avalon Logkit logger做为日志记录器,也可以用 Jakarta Log4j logger.首先它会在classpath中查找Logkit. 找不到,会再尝试Log4j.
1.一般的可选日志功能:
Default Configuration
默认在当前目录下创建日志文件.
Existing Log4j Category
从1.3开始, Velocity 可以将日志输出到Log4j配置中. 但你必须:
1.       确认Log4j jar is in your classpath. (你应一直这样做,自从使用Velocity.)
2.       配置Velocit使用SimpleLog4JLogSystem class.
3.       通过 'runtime.log.logsystem.log4j.category' 参数指定日志条目名字.
这里不建议使用老的Log4JLogSystem class. 可以在随后看到示例.
Custom Standalone Logger
你可以创建定制的日志类 – 你只需简单的实现接口org.apache.velocity.runtime.log.LogSystem然后将你的实现类名配置到运行时参数 runtime.log.logsystem.class的值, Velocity在init()时将创建你的日志实例. 更多相关信息可以看 Velocity helper class 和 configuration keys and values. 要注意的是, 接口org.apache.velocity.runtime.log.LogSystem 在1.2后才支持这一功能.
Integrated Logging
你可以将Velocity的日志和你现存系统的日志整合到一起.
Using Log4j With Existing Category
这里是一个使用Log4j做为Velocity日志的例子.
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;

import org.apache.log4j.Category;
import org.apache.log4j.BasicConfigurator;

public class Log4jCategoryExample
{
    public static String CATEGORY_NAME = "velexample";

    public static void main( String args[] )
        throws Exception
    {
        /*
         * configure log4j to log to console
         */

        BasicConfigurator.configure();

        Category log = Category.getInstance( CATEGORY_NAME );

        log.info("Hello from Log4jCategoryExample - ready to start velocity");

        /*
         * now create a new VelocityEngine instance, and
         * configure it to use the category
         */

        VelocityEngine ve = new VelocityEngine();

        ve.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
            "org.apache.velocity.runtime.log.SimpleLog4JLogSystem" );

        ve.setProperty("runtime.log.logsystem.log4j.category", CATEGORY_NAME);

        ve.init();

        log.info("this should follow the initialization output from velocity");
    }
}
上面的例子可以在examples/logger_example.下找到.
2.Simple Example of a Custom Logger
这是一个定制实现你自己的日志记录器,并将其加入到Velocity的日志系统中. LogSystem interface—只需要支持这个接口.
import org.apache.velocity.runtime.log.LogSystem;
import org.apache.velocity.runtime.RuntimeServices;
...

public class MyClass implements LogSystem
{

...

    public MyClass()
    {
        ...

        try
        {
            /*
             * register this class as a logger
             */
            Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, this );
            Velocity.init();
        }
        catch (Exception e)
        {
            /*
             * do something
             */
        }
    }

    /**
     * This init() will be invoked once by the LogManager
     * to give you current RuntimeServices intance
     */
    public void init( RuntimeServices rsvc )
    {
        // do nothing
    }

    /**
     * This is the method that you implement for Velocity to call
     * with log messages.
     */
    public void logVelocityMessage(int level, String message)
    {
        /* do something useful */
    }
...
}
12.Configuring Resource Loaders(资源装载器配置)
1.Resource Loaders
Velocity一个非常重要的基础功能是资源管理和装载. 这里资源 'resources' 不仅包括了模板('templates'),RMS也可以处理非模板文件, 特别是在使用 #include() 指令时.
resource loader system (资源装载系统)很容易扩展,可以同时执行多个资源装载器的操作. 这极大的方便了资源管理, --你可以根据需要,定制自己的资源装载器.
Velocity当前包含4种资源管理器, 说明如下:(注意例程中的配置参数有一个loader配置名 (ex.'file' in file.resource.loader.path).这个 'common name' 配置不一定会在你的系统中工作. 具体可见 resource configuration properties 理解系统如何工作. 这每一个loader都在包 org.apache.velocity.runtime.resource.loader. 中
FileResourceLoader : 这个loader从文件系统取得资源,其配置参数如下:
file.resource.loader.path = <path to root of templates>
file.resource.loader.cache = true/false
file.resource.loader.modificationCheckInterval = <seconds between checks>
这是己配置的默认装载器, 默认从当前目录('current directory'). 但当你不想将模板入到servlet容器的启动目录下时,这个loader就无能为力了。请参看 developing servlets with Velocity.
JarResourceLoader : 这个loader可以从jar文件包中取得资源,在你把你的模板文件全部打包成 jar包时,系统会用这个loader来提取. 配置基本一样除过jar.resource.loader.path, 这里或以使用标准的JAR URL syntax of java.net.JarURLConnection.
ClasspathResourceLoader : 从classloader中取得资源. 一般来说,这意味着ClasspathResourceLoader将从classpath中load templates.这是在Servlet类型应用常见的一种设置。支持Servlet 2.2 (或更新)规范的容器Tomcat就是这样一个例子. 这种装载方式很有效, 因此你必须将你的模板打成jar包放到你的web应用的WEB-INF/lib 目录下.就不再存在绝对、相对路径的问题了,与以上两个装载器相比 ClasspathResourceLoader不仅在servlet container中用也,几乎所有应用的上下文(context)都有用.
DataSourceResourceLoader : 这个loader可以从数据库载入资源. 这个loader不是标准j2EE的一部分,因此需要取得J2EE 发行库,将j2ee.jar加入到build/lib目录下,然后编译新的Velocity.jar设置ant target为jar-j2ee,更细说明请见文档中对类 org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader的介绍.
2.Configuration Examples
己配置的loader,可以参看 resource configuration section, for further reference.
第一就是要配置loader的名字. 参数resource.loader的值可以是你喜欢的用来关联指定loader的名字.
resource.loader = file
下一步就是设置这个名字对应的class了,这是最重要的一步 :
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader

这个例子中,我们告诉Velocity我们设置的loader名字叫file,指定的类是org.apache.velocity.runtime.resource.loader.FileResourceLoader.下一步就是设置这个loader的一些重要参数.
file.resource.loader.path = /opt/templates
file.resource.loader.cache = true
file.resource.loader.modificationCheckInterval = 2

这里,我们设置了查找模板的路径是 /opt/templates. 然后打开caching,最后,设置检测周期为2秒,以便Velocity检测新的或己更改过的模板来load.
上示是一些基本配置,随后,还会再有一些示例.
Do-nothing Default Configuration : 你也可以什么都不改动,就用默认的配置. 这是默认的loader配置:
引用
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 = 0

Multiple Template Path Configuration :多模板路径配置如下所示,只要用逗号分开就是 :
引用
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 = /opt/directory1, /opt/directory2
file.resource.loader.cache = true
file.resource.loader.modificationCheckInterval = 10

Multiple Loader Configuration : 多个loader配置,嗯,也很简单,不说了,看例子就是.
#
引用

# specify three resource loaders to use
#
resource.loader = file, class, jar

#
# for the loader we call 'file', set the FileResourceLoader as the
# class to use, turn off caching, and use 3 directories for templates
#
file.resource.loader.description = Velocity File Resource Loader
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = templatedirectory1, anotherdirectory, foo/bar
file.resource.loader.cache = false
file.resource.loader.modificationCheckInterval = 0

#
# for the loader we call 'class', use the ClasspathResourceLoader
#
class.resource.loader.description = Velocity Classpath Resource Loader
class.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

#
# and finally, for the loader we call 'jar', use the JarResourceLoader
# and specify two jars to load from
#
jar.resource.loader.description = Velocity Jar Resource Loader
jar.resource.loader.class = org.apache.velocity.runtime.resource.loader.JarResourceLoader
jar.resource.loader.path = jar:file:/myjarplace/myjar.jar, jar:file:/myjarplace/myjar2.jar
只是注意: 'file', 'class', and 'jar' 这三个名字不是固定是,可以根据你的喜好来设定. 但只要保持上面的对应关系就是.
3.插入定制资源管理器和Cache实现
资源管理器是相关资源 (template and static content)管理系统的核心部分, 它为应用程序取得请求模板,查找他们的有效资源loaders,操作caching.对于高级用户,可以用自定制的caching系统取代这个默认的实现.
资源管理器必须实现 org.apache.velocity.runtime.resource.ResourceManager interface. 具体描述请看api文档. 尽量使用默认实现,除非你认为有必要在以下参数中换成你自己的 :
resource.manager.class

这个参数也可通过RuntimeConstants.RESOURCE_MANAGER_CLASS 设定。
资源的caching必须实现 org.apache.velocity.runtime.resource.ResourceCache interface 接口,配置到参数中是 :
resource.manager.cache.class
这个参数也可通过 RuntimeConstants.RESOURCE_MANAGER_CACHE_CLASS 设定

13.Template Encoding for Internationalization(字符编码和国际化)
从版本1.1开始, 可以设定资源的编解码类型. 在API中也可以传入解码的方式 :
org.apache.velocity.servlet.VelocityServlet :
public Template getTemplate( String template, String encoding )
org.apache.velocity.app.Velocity :
public static Template getTemplate(String name, String encoding)
public static boolean mergeTemplate( String templateName, String encoding, Context context, Writer writer )
encoding 参数可以设定为JVM支持的某个值 "UTF-8" or "ISO-8859-1".关于字符集正式的名字, see here.
注意,这仅仅是编码了模板自己 – 输出的编码由应用程序指定.

14.Velocity and XML

Velocity's的VTL( velocity template language)处理XML数据很方便. Anakia是一个用XSL从XML中输出视图的例子. Velocity站点,文档包括 Jakarta site is also rendered using Anakia.
一般来说,处理XML会用到 JDOM 这样的东东将XML转成java数据结构 ,如下例示是一个XML文档 :
引用
<?xml version="1.0"?>

<document>
<properties>
<title>Developer's Guide</title>
<author email="geirm@apache.org">Velocity Documentation Team</author>
</properties>
</document>

一小段处理的读取XML的java程序如下:
...

SAXBuilder builder;
Document root = null;

try
{
    builder = new SAXBuilder( "org.apache.xerces.parsers.SAXParser" );
    root = builder.build("test.xml");
}
catch( Exception ee)
{}

VelocityContext vc = new VelocityContext();
vc.put("root", root );

...

(See the Anakia source for details on how to do this, or the Anakia example in the examples directory in the distribution.) 现在,在模板中应用 :
引用
<html>
<body>
    The document title is
    $root.getChild("document").getChild("properties").getChild("title").getText()
</body>
</html>


就像渲染一般模板那样, 使用 Context 中的JDOM tree. 虽然这个例子看起来不漂亮, 但它展示了这样做是多么容易.
引用
One real advantage of styling XML data in Velocity is that you have access to any other object or data that the application provides. You aren't limited to just using the data present in the XML document. You may add anything you want to the context to provide additional information for your output, or provide tools to help make working with the XML data easier. Bob McWhirter's Werken Xpath is one such useful tool - an example of how it is used in Anakia can be found in org.apache.velocity.anakia.XPathTool.
One issue that arises with XML and Velocity is how to deal with XML entities. One technique is to combine the use of Velocimacros when you need to render an entity into the output stream :
## first, define the Velocimacro somewhere

#macro( xenc $sometext )$tools.escapeEntities($sometext)#end

## and use it as

#set( $sometext = " < " )
<text>#xenc($sometext)</text>
where the escapeEntities() is a method that does the escaping for you. Another trick would be to create an encoding utility that takes the context as a constructor parameter and only implements a method:
public String get(String key)
{
    Object obj = context.get(key)
    return (obj != null) ? Escape.getText( obj.toString() ) : "";
}

Put it into the context as "xenc". Then you can use it as :
<text>$xenc.sometext</text>

This takes advantage of Velocity's introspection process - it will try to call get("sometext") on the $xenc object in the Context - then the xenc object can then get the value from the Context, encode it, and return it.
Alternatively, since Velocity makes it easy to implement custom Context objects, you could implement your own context which always applies the encoding to any string returned. Be careful to avoid rendering the output of method calls directly, as they could return objects or strings (which might need encoding). Place them first into the context with a #set() directive and the use that, for example :
#set( $sometext = $jdomElement.getText() )
<text>$sometext</text>

The previous suggestions for dealing with XML entities came from Christoph Reck, an active participant in the Velocity community. We are very grateful for his [unknowing] contribution to this document, and hope his ideas weren't mangled too badly

15.FAQ (Frequently Asked Questions)
开发中常见的问题解答.
1.Why Can't I Access Class Members and Constants from VTL?
在VTL中无法访问到类的数据域
最简单的原因是我们无法反射/内省(introspect )这个对象.因为就OOP来说,对象中要隐藏自己没有必要外露的数据或命令.解决方法:包状成publicly 命令反回它,保证它是公开访问的. 当然,你要保证能改动源文件, 否则,就要用工具来解析它. org.apache.velocity.app.FieldMethodizer是用来解析你的类的, 如下示例如何将一个public static fields 导出到模板中.假设你的类是 :
public class Foo
    {
        public static String PATH_ROOT = "/foo/bar";

        ....
    }

你可这样将它放入context中:
context.put("myfoo", new FieldMethodizer( new Foo() ) );

然后在模板中就可以java代码的风格来访问 :
$myfoo.PATH_ROOT

如果你需要访问public的非静态域时(public non-static members)甚止是私有成员!那你就必须扩展或重写 FieldMethodizer 这个类----但你为什么要搞得这么复杂呢?
2.Where does Velocity look for Templates?
Velocity到哪里提取模板文件?
默认的,不做任何配置更改的情况下,Velocity会在当前目录下或相对与当前目录(如'foo/bar.vm')下查找.
Velocity对这些都是自动处理的. Velocity只记住它自己的一个root目录,这个概念不同与多根目录的文件系统(like - "C:\", "D:\", etc).

16.Summary
希望这个指南能帮助您出色的将velocity应用到项目中. 请将您的意见反馈发送到mail lists.


17.Appendix 1 : Deploying the Example Servlet
布署本文中的Servlet例程
Servlet开发者经常受到的一个打击是将servlet放错了地方---一切都是好的除此之外. 使用Tomcat 、 Resin i这样的Servlet容器都可以运行起我们的SampleServlet . SampleServlet.java 在目录 examples/servlet_example 下. 虽然有些servlet engines (Resin, for example) 会自动将它编译,但是为了学习,还是你亲自动手先将它编译过.
Jakarta Tomcat
Jakarta Tomcat 的安装就不多说了. 'webapp' 目录是tomcat默认的查找它的web应用的root.所以,以下是我们要做的:
首先,创建一个新的 'webapp' 暂时名叫 velexample 放到Tomcat的webapps 目录下, 这个新的目录结构如下 :
引用
velexample
velexample/WEB-INF
velexample/WEB-INF/lib
velexample/WEB-INF/classes
将Velocity jar 放到velexample/WEB-INF/lib下. (从1.2版本后,所有相关依赖包都打包在. velocity-dep-1.2.jar中),当然,相关的依赖包也必须放到WEB-INF/lib下. 具体可以看 "Getting Started" and "Dependencies", 这两节的介绍.
将编译过的SampleServlet.class放到 velexample/WEB-INF/classes 下.
将sample.vm 放到目录velexample 下.
现在就可以启动servlet来访问servlet了.
在Browser中输出如下 :
http://localhost:8080/velexample/servlet/SampleServlet
如不能工作,则试下 :
http://<your computer's ip address>:8080/velexample/servlet/SampleServlet
看到输出结果了吗?.[/size]
分享到:
评论

相关推荐

    《Velocity java开发指南》中文版

    《Velocity java开发指南》中文版《Velocity java开发指南》中文版《Velocity java开发指南》中文版《Velocity java开发指南》中文版《Velocity java开发指南》中文版《Velocity java开发指南》中文版《Velocity ...

    velocity Java开发指南中文版

    velocity Java开发指南中文版 格式:pdf 希望能对你有所帮助

    velocity文档(Velocity1.4java开发指南中文版,Velocity1.4模板使用指南中文版中文版)

    Velocity1.4java开发指南中文版 Velocity1.4模板使用指南中文版中文版

    Velocity java开发指南

    Velocity java开发指南 Velocity是一种基于java的一个模版引擎。

    velocity+Java开发指南中文版.zip

    velocity+Java开发指南中文版.zip velocity velocity.pdf velocity开发指南 velocity帮助文档

    《Velocity1.4 java开发指南》中文版

    10.Velocity Configuration Keys and Values(配置参数名字和值说明) 20 1.Runtime Log 20 2.字符集编码问题 21 3.#foreach() Directive 21 4.#include() and #parse() Directive 21 5.资源管理 21 6.Velocimacro(宏...

    Velocity Java开发指南中文版

    Velocity 是一处基于java 语言的模板引擎, 使用这个简单、功能强大的开发工具,可以很容易的将数据对象灵活的 与格式化文档组装到一起;希望本文能指引使用velocity 在开发基于servlet 或一般java 应用程序的应用上...

    velocity+Java开发指南中文版

    velocity+Java开发指南中文版 本书共分17章,是一本很不错的图书

    Velocity_java开发指南

    Velocity_java开发指南

    velocity经典4pdf中文教程

    内容包括: 《Velocity模板使用指南中文版》 《VTL语法参考指南中文版》 《Velocity Web应用开发指南中文版》 《velocity Java开发指南中文版》

    JAVA的Velocity语法学习

    JAVA的Velocity语法学习 内涵《Velocity_java开发指南》《Java的模板引擎Velocity初体验》 以及所必须的jar ,和大家一块学习,很好哦

    Velocity学习指南(中文版).rar

    Velocity用户指南旨在帮助页面设计者和内容提供者了解Velocity和其简单而又强大的脚本语言(Velocity Template Language (VTL))。本指南中有很多示例展示了用Velocity来讲动态内容嵌入到网站之中,但是所有的VTL ...

    velocity学习文档

    《velocity Java开发指南中文版》 《Velocity Web应用开发指南中文版》 《Velocity模板使用指南中文版》

    velocity文档

    《Velocity java开发指南》中文版,

    Velocity 帮助文档大全(打包)

    本人搜集的Velocity相关的所有帮助文档,包括: 《Velocity Web应用开发指南中文版.pdf》、 《Velocity+Java开发指南中文版.pdf》、 《Velocity模板使用指南中文版.pdf》、 《VTL语法参考指南中文版.pdf》

    Velocity 资料汇总

    Velocity Java开发指南中文版 Velocity Web应用开发指南中文版 Velocity模板使用指南中文版 VTL语法参考指南中文版 DB4O系统应用之起步篇 velocity用户手册 velocity语法 velocity初探 velocity1.5帮助说明 velocity...

    Velocity 模板使用指南

    当Velocity应用于web开发时,界面设计人员可以和java程序开发人员同步开发一个遵循MVC架构的web站点,也就是说,页面设计人员可以只 关注页面的显示效果,而由java程序开发人员关注业务逻辑编码。Velocity将java...

    velocity教程

    velocity语法,Velocity+Java开发指南中文版,struts2 与velocity1.6及velocity tools1.4的整合,Velocity+Spring+Ibatis框架搭建说明文档,Velocity详解(初学者建议看)

Global site tag (gtag.js) - Google Analytics