Documentation regarding Custom Utility Class for Velocity
"O. Olson" <[email protected]> Thu, 8 Aug 2013 17:06:18 +0100 (BST)
| Newsgroups | gmane.comp.jakarta.velocity.user |
|---|---|
| Message-ID | <[email protected]> |
Hi,
I am wondering if there is any documentation on writing your own Utility Class or Custom Tool to add to Velocity. The only place I found some help is http://www.sergiy.ca/how-to-create-custom-tools-for-apache-velocity/ (There is something regarding Custom Tools at http://velocity.apache.org/tools/releases/2.0/creatingtools.html - but I could not find anything regarding Utility Classes that we can push into the Velocity Context.)
Originally, I was thinking of doing my processing/customization in Velocimacros, but that is turning out to be a bit more complex/cumbersome than I expected. I am thinking of doing this in Java, and pushing the results to the Velocity Context as a single object/utility class instance. For purposes of discussion let us assume, I do something like the following in Java:
VelocityContext context;
context.put("myUtil", new MyUtil());
I'd appreciate if I could get answers/ideas on:
1. I am wondering if MyUtil() needs to be static across requests. I intend MyUtil() to provide easy access and manipulation of the current request. Hence, I would probably do something like the following in Java:
context.put("myUtil", new MyUtil(currentWebRequest));
i.e. I would instantiate MyUtil with the current Web Request. MyUtil could then provide easy access to say the Number of Rows in the Request. So in the Template I could do:
$myUtil.NumRows
If MyUtil() is static, this would not work, because different requests would have different number of Rows. Should the Utility Class/Object be static? The example mentioned above shows only static methods, hence my question.
2. Should my Utility class follow the bean syntax i.e. for the above example of $myUtil.NumRows in the template, would I need to declare something like the following in the MyUtil Java class:
public int getNumRows() { }
3. What would be a good way to pass a Constant from Java to the Template? Should I use the bean syntax again? E.g. in the template
$myUtil.JAVA_CONSTANT
Would I need to have something like:
public int getJAVA_CONSTANT () { }
Thank you in advance for your help,
O. O.