pt., 2 sty 2026 o 21:54 Christopher Schultz
<[email protected]> napisał(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/org/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 = new DateTool();
      private static final MathTool MATH_TOOL = new MathTool();
      private static final NumberTool NUMBER_TOOL = 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="struts.velocity.contexts"
            value="com.example.velocity.ToolsVelocityContext"/>

  Or in struts.properties:
  struts.velocity.contexts=com.example.velocity.ToolsVelocityContext

4: Use in templates:
Today: $date.format("yyyy-MM-dd")
Result: $math.add(1, 2)


Cheers
Łukasz

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to