Re: Trouble getting Velocity Tools tools to work as expected
Lukasz Lenart <[email protected]> Sat, 3 Jan 2026 07:56:46 +0100
| Newsgroups | gmane.comp.jakarta.struts.user |
|---|---|
| Message-ID | <CAMopvkPEk+GkKF22K=oKpaYE3vLhB2zPeN99Vty0Unc2n7B0qA@mail.gmail.com> |
pt., 2 sty 2026 o 21:54 Christopher Schultz <[email protected]> napisa=C5=82(a): > I can confirm that Velocity is running because I have a few #if > predicates in there and they aren't rendering as literals, but I think > I'm not getting the toolbox loaded. There is a bug in Struts' VelocityTools as far as I understand, the context is only created for the DEAFULT_SCOPE which means "request" https://github.com/apache/struts/blob/main/plugins/velocity/src/main/java/o= rg/apache/struts2/views/velocity/VelocityTools.java#L56 Feel free to register a bug in JIRA > I have a handful of tools that don't need to be instantiated once for > every request and I'd prefer to keep a single instance of them in the > application scope. Is that possible without writing a > ServletContextListener and manually-injecting things into the > application scope? Here is a simple workaround without using tools.xml (sorry for not having a documentation for this :( ) 1. Remove or don't use struts.velocity.toolboxlocation 2. Create a custom VelocityContext class: package com.example.velocity; import org.apache.velocity.VelocityContext; import org.apache.velocity.tools.generic.DateTool; import org.apache.velocity.tools.generic.MathTool; import org.apache.velocity.tools.generic.NumberTool; /** * Custom VelocityContext that provides application-scoped tools. * Tools are instantiated once and reused across all requests. */ public class ToolsVelocityContext extends VelocityContext { // Static tool instances (application scope - singleton) private static final DateTool DATE_TOOL =3D new DateTool(); private static final MathTool MATH_TOOL =3D new MathTool(); private static final NumberTool NUMBER_TOOL =3D new NumberTool(); public ToolsVelocityContext() { // Add your application-scoped tools put("date", DATE_TOOL); put("math", MATH_TOOL); put("number", NUMBER_TOOL); } } 3: Configure in struts.xml or struts.properties: <!-- struts.xml --> <constant name=3D"struts.velocity.contexts" value=3D"com.example.velocity.ToolsVelocityContext"/> Or in struts.properties: struts.velocity.contexts=3Dcom.example.velocity.ToolsVelocityContext 4: Use in templates: Today: $date.format("yyyy-MM-dd") Result: $math.add(1, 2) Cheers =C5=81ukasz