Velocity1.4 Java Development guide Chinese Version

Source: Internet
Author: User

1. Getting Started

Velocity is a Java-based template engine. Using this simple and powerful development tool, you can easily assemble data objects flexibly with formatted documents; we hope this article will guide you to use velocity to quickly start developing servlet-based or general Java applications.

1. Getting Started

It is easy to get velocity and start running on your machine. The following is a full description:

Get the velocity release, go here.

Directory and file Description: The complete Velocity-X.jar velocity jar package is generally named in velocity-X.jar, where X is the current version number. Note that this jar package does not contain other jar packages that velocity must depend on (For details, refer to the following section ).

SRC: complete source file code directory

Examples. Complete aplication or web app example.

Docs: veocity document directory

Build: The LIB required for compiling source code with ant.

 

 

OK, now you can start using it. Put the Velocity-x.jar in your classpath or webapp Lib.

 

Of course, we strongly recommend that you first run the example to see the advantages of velocity.

2. dependencies dependent resources

Velocity can run in jdk1.4 or jre1.4 and later versions.

Velocity also depends on some other jar packages, which are available in build/lib of the distribution version. If you download a binary distribution version, you need to download other dependent packages at the following address.

Jakarta commons collections-required.

Jakarta aveon logkit-optional, but it is recommended to add a strong column to output log information.

Jakarta Oro-optional, only when the org. Apache. Velocity. Convert. webmacro template conversion tool is used.

 

2. Reference resources:

The following lists some excellent resources and routines:

Developer email list mail-lists.

Email portfolio: http://www.mail-archive.com is a good resource library. You can search with 'velocity 'as the keyword.

Source code (source code distribution version): src/Java/...: all source code containing the velocity Project

Application routine 1: Examples/app_example1: a simple example of how to use velocity in general applications.

Application routine 1 2: Examples/app_example2: How to Use the velocity tool class in the application.

Servlet example: examples/servlet_example1: How to Use velocity to output a template in servlet.

Logger example: examples/logger_example: How to customize the Velocity Log tool.

XML example: examples/xmlapp_example: Use JDOM to read content from the velocity template. It also contains an example of recursive macro call.

Event example: examples/event_example: Use the event processing API in velocity 1.1.

Anakia application: examples/anakia: the example uses stylesheet to beautify XML data.

Forumdemo web app: examples/forumdemo: a servlet-based forum function implementation example.

Templates: Test/templates: a set of templates for the VTL (velocity template lanauage) function.

 

Context example: examples/context_example: two examples of how to override (inherit) the velocity Context Function (for advanced users ).

 

3. How does it work?

1. Basic usage mode

To use velocity in application program or servlet, follow these steps:

For all applications, the first step is to initialize velocity. Generally, the unique instance mode (Singleton) is used, such as velocity. INIT ().

Create a context object.

Add your data object to the context object.

Use velocity to select a template.

The merge template and data are exported to the output stream.

 

The following code combines output by using the single-instance mode org. Apache. Velocity. App. velocity:

 

Import java. Io. stringwriter;

Import org. Apache. Velocity. velocitycontext;

Import org. Apache. Velocity. template;

Import org. Apache. Velocity. App. velocity;

Import org. Apache. Velocity. Exception. resourcenotfoundexception;

Import org. Apache. Velocity. Exception. parseerrorexception;

Import org. Apache. Velocity. Exception. methodinvocationexception;

 

// Initialization

Velocity. INIT ();

// Obtain the velocitycontext object

Velocitycontext context = new velocitycontext ();

// Add data objects to the context to be used in the template

Context. Put ("name", new string ("velocity "));

Template template = NULL;

// Select the template to use

Try

{

Template = velocity. gettemplate ("mytemplate. VM ");

}

Catch (resourcenotfoundexception rnfe)

{

// Couldn't find the Template

}

Catch (parseerrorexception pee)

{

// Syntax error: Problem parsing the Template

}

Catch (methodinvocationexception MIE)

{

// Something invoked in the template

// Threw an exception

}

Catch (exception E)

{}

 

Stringwriter Sw = new stringwriter ();

// Merge output

Template. Merge (context, SW );

 

The above is the basic usage mode and looks very simple! These are the steps required to use velocity in general, but you may not want to write code in this step-by-step manner-velocity provides some tools that are easier to use in servlets or applications. Later in this Guide, we will discuss better usage in Servlet and common applications.

 

4. Single Instance or multiple instances (to singleton or not to singleton ...)?

1. Singleton Model

This is the default mode of the system, so that only one velocity engine instance exists in the JVM (Application) or web aplication (a web program) for sharing .. This is very convenient for configuring and sharing resources. for example, in Web applications that support servlet 2.2 +, each web app holds its own unique velocity instance, which can share resources such as templates and a logger. singleton can directly use Org. apache. velocity. app. the velocity class is as follows:

Import org. Apache. Velocity. App. velocity;

Import org. Apache. Velocity. template;

 

/*

* Configure the engine-as an example, we are using

* Ourselves as the logger-see logging examples

*/

 

Velocity. setproperty (velocity. runtime_log_logsystem, this );

 

/*

* Now initialize the engine

*/

 

Velocity. INIT ();

 

 

Template T = velocity. gettemplate ("foo. VM ");

2. separate instance

After version 1.2 .) create, configure, and use multiple velocity instances. This is very convenient when you want to configure their template directories, loggers, and other resources independently in the same program. org. apache. velocity. app. velocityengine class. the following is an example. Note the difference between singleton example and Singleton example:

Import org. Apache. Velocity. App. velocityengine;

Import org. Apache. Velocity. template;

 

...

 

/*

* Create a new instance of the engine

*/

 

Velocityengine VE = new velocityengine ();

 

/*

* Configure the engine. In this case, we are using

* Ourselves as a logger (see logging examples ..)

*/

 

Ve. setproperty (velocityengine. runtime_log_logsystem, this );

 

/*

* Initialize the engine

*/

 

Ve. INIT ();

 

...

 

Template T = VE. gettemplate ("foo. VM ");

As you can see, this is very simple to use directly. No matter you use Singleton or separate instances, you do not need to change the upper layer structure and template content of your program.

For developers, you should use either of the following two classes

Org. Apache. Velocity. App. velocity is applied to singleton model and org. Apache. Velocity. App. velocityengine ').

 

 

5. The context

1. the basics

'Context' is a core concept in velocity. It is a common concept derived from the system's "a container of data. the context plays the carrier role between the Java program layer and the template view layer (or the designer.
As a programmer, you can put different types of data objects generated by your program into context. For view design, these objects (including their data domains and commands) will be referenced in the template element (references ). In general, you will work with the view designer to determine the data required by the application. It can be said that the data object you put into the context becomes an "API", which is accessed by the view designer in the template. therefore, when deciding which data objects to put to the context, the program designer needs to carefully analyze the data content required for the view performance.

Although you can create your own context class in velocity to support some personalized applications (for example, an access to save the LDAP server service context ), you can implement the velocitycontext, which has encapsulated the base class of relatively complete services.

The velocitycontext object can basically satisfy most applications. We strongly recommend that you do not create your own context unless in special circumstances!

The usage of velocitycontext is very simple, similar to hashtable class. Below are two basic usage provided by this interface:

Public object put (string key, object value );

Public object get (string key );

Like hashtable, the value here must be a java. lang. object Class (cannot be the original type, such as Int or Boolean) or a null value. the original type (fundamental types like Int or float) must be encapsulated as an appropriate object type.

OK. The above is the usage concept of the context object. It is very simple, but it is so embarrassing :). For more information, see API documentation.

2. Use the # foreach command in the template to support iterative objects

Before adding the context, you have full operation freedom to the object. but like all freedom, you must abide by some rules and assume some responsibilities. Therefore, you must understand how velocity uses objects, velocity VTL supports multiple Collection types (Collection types) # foreach ().

Object [] a general object array. Velocity encapsulates the internal function into an iterator interface object. This conversion does not involve programmers or view designers.

Java. util. collection: velocity uses their standard iterator () to get an iterator object that can be used in iteration. If you use your own collection interface object, make sure that its iterator () command to return an available iterator.

Java. util. map interface object. Velocity uses the values () command of its top-level interface to obtain an object that implements the collection interface, and applies its iterator () to return an iterator.

Java. util. NOTE: If an iterator object is placed in the context, when there are multiple # foreach () instructions in the template, these # foreach () will be executed in sequence, if the first call fails, the subsequent call will be blocked and cannot be reset.

Java. util. enumeration use with caution: Like java. util. in the same way as iterator, velocity will use an object that cannot be reset ('non-resettablity ') or a final type.

 

Therefore, it is only necessary for iterator and enumeration objects to be put into context unless they are self-defeating. Maybe you have a better way not to use them.

For example, you can run the following code:

Vector v = new vector ();

V. addelement ("hello ");

V. addelement ("there ");

 

Context. Put ("Words", V. iterator ());

 

Replace:

Context. Put ("Words", V );

 

3. Context chaining

Another new concept is context chaining. it is also called context wrapping (a bit similar to the chain in servlet). This advanced feature allows you to link Multiple independent velocity contexts for use in the template.

The following is a sample code for this usage:

Velocitycontext context1 = new velocitycontext ();

 

Context1.put ("name", "velocity ");

Context1.put ("project", "Jakarta ");

Context1.put ("DUPLICATE", "I am in context1 ");

 

Velocitycontext context2 = new velocitycontext (context1 );

 

Context2.put ("Lang", "Java ");

Context2.put ("DUPLICATE", "I am in context2 ");

 

Template. Merge (context2, writer );

In the above Code, context2 serves as the chains of context1. this means that you can use any object in the two contexts in the template. When the two contexts have the same key and are output in the template, the value of the last key is output. In the preceding example, the value of key duplicate is output as "I am in context2 ".

In the preceding example, there is no duplication, or 'covering'. the string "I am in context1" in context1 can still be obtained through the context1.get ("DUPLICATE") method. in the preceding example, if '$ DUPLICATE' is referenced in the template,' I am in context2 'is returned, and the template cannot access' I am in context1' in context1 '.

In addition, when you try to add information to the template, such as using the # Set () statement, this will affect the output template.

As mentioned above, the velocity context class is also or extended, but not described in this Guide. if you are interested, you can view Org. apache. velocity. the code in context to understand how contexts is generated and how Java data objects are transmitted. examples of routine examples/context_example are provided.

4. Created objects in the template

There are two common ways to interact between data objects and templates in Java code:

The template designer executes the command from the template for the Java object put into the context by the programmer:

# Set ($ myarr = ["A", "B", "C"])

$ Foo. Bar ($ myarr)

When the template adds an object to the context and the template combines the output, the Java code can access these objects.

# Set ($ myarr = ["A", "B", "C"])

# Set ($ Foo = 1)

# Set ($ bar = "bar ")

The skills mentioned here are too early, but you must understand the following concepts:

The VTL uses the [1 .. 10] And objectarray ["A", "B"] is Java. util. arraylist object. therefore, you must be compatible with the command design of your object.

Numbers will be packaged as integers and strings in context. Of course, it is strings.

Velocity will adapt to the call command of the object according to the called parameter type. setfoo (int I) will put an int into the context and # Set () will not conflict.

 

5. other usage of the context object

Every velocitycontext (or any object originating from abstractcontext) is a storage node that encapsulates specified rules. but here are some features you should know:

Consider the following:

Your template uses velocitycontext object repeatedly.

Template caching is off.

Call the gettemplate () command repeatedly.

 

This may cause memory leakage of velocitycontext ('leak' memory)-When it collects too many data objects, it is strongly recommended that you do the following:

Create a new velocitycontext in template render process. this prevents excessive cache data. when you need to reuse a velocitycontext because it has placed data objects, you just need to wrap it like this: velocitycontext usethis = new velocitycontext (populatedvc ); for more information, see context chaining.

Enable the caching function of the template to prevent repeated parsing of the template. Of course, this requires the server to have higher performance.

 

Template objects must be reused during iterative operations. this will not put too much pressure on velocity. If the cache is disabled, you need to read and parse the template each time, resulting in a large amount of new information to be saved in velocitycontext each time.

 

6. Using Velocity in servlets

1. servlet Programming

Velocity is most commonly used in Servlet as WWW Service. there are many reasons to tell you that this task is most suitable for velocity to complete. The most important one is that velocity's can separate the view (presentation layer and) code layer. here we can see more reasons for this.

Using Velocity in servlet is very simple. You only need the velocityservlet class of extend and a required implementation method: handlerequest ().

 

Paste some content. For other content, see the attachment and click to download.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.