Python Rocks! and other rants - Java 18.5.2004
Weblog of Kent S Johnson

2004-05-18

Velocity and Velocity Tools releases

The Jakarta Velocity project has recently released new versions of both the main Velocity package and the Velocity Tools sub-package. Velocity is a flexible, powerful and easy-to-use template engine that can be used for any kind of text generation including web pages, XML files and code generation. Velocity Tools includes modules that integrate Velocity with Struts and allow Velocity to be used as an alternative to JSP for Struts views. Velocity's simple, uncluttered syntax makes it a very readable alternative to JSP.

Velocity has a built-in introspection engine that makes it suitable for generating text output from any kind of domain data. In particular it is a great way to generate XML from a Java object model. All the XML markup goes in the template file instead of cluttering up your code. *

I have used Velocity on many projects for report generation, web page generation, and output file formatting. I highly recommend it.

With the new releases, this is a great time to take a look at these packages.

[*]: Of all the ways to generate XML from a Java object model, I think Velocity is one of the best. Just like with web page generation, it separates content and presentation and keeps the markup out of your code. Here are some alternatives:
  • If your data is in a DOM model already, you can serialize it with DOM tools. This works as a way to persist your data. For custom formatting you need to transform the data, for example using XSL.
  • You can build a DOM model and serialize it. That is a lot of work just to generate a file.
  • To serialize a custom model you can use one of the many Java-to-XML mapping products such as Castor XML Mapping or JAXB. Again, this works for persistence but it is hard to generate a custom format from it.
  • You can write code to generate the XML directly or using a helper library such as XMLWriter. This is painful in several ways. It puts the markup in the code, which is not such a good idea. You have to manually match up begin and end tags, which is difficult and error-prone. There is no good place for the code - it doesn't feel right either in the data classes or as a separate module.
  • Or (drum-roll, please) you can write a Velocity template to generate the XML. In code, you just need a little boilerplate to set up the template engine and run the template. All the XML structure is in one place, in the template file. You have full access to the data using Velocity introspection. You can add more output formats just by creating new templates and hooking them in to the code. Life is good!
posted at 07:52:32    #    comment []    trackback []
May 2004
MoTuWeThFrSaSu
      1 2
3 4 5 6 7 8 9
10111213141516
17181920212223
24252627282930
31      
Apr
2004
 Jun
2004

Everything Java

XML-Image Letterimage

BlogRoll

© 2004, Kent Johnson