There is a ResourceLoader
class in the API documentation:
I would like to implement my own loader, because I need to load templates from a database, but in a context sensitive way (in other words: DataSourceResourceLoader cannot be used, I need to write custom code to select the "right" template from the database).
It seems that ResourceLoader
has some abstract methods, and it also seems that I would be able to write a custom loader by implementing these abstract methods. But I don't see any way to add a new loader to the engine. There is no "addResourceLoader" method. The documentation only shows how to configure the loaders that are built into Velocity:
https://velocity.apache.org/engine/2.0/developer-guide.html#resource-loaders
The main question: how to I add a custom resource loader to VelocityEngine (or VelocityContext?)
Another side question: I would like to turn off all built-in loaders. Especially WebappResourceLoader
which is active by default, and represents a security risk in my particular application. How to do that?
You must first implement the ResourceLoader interface (or subclass an existing resource loader), then declare your resource loader in velocity.properties
:
resource.loader = .... , my_loader, ...
my_loader.resource.loader.class = com.foo.MyResourceLoader
my_loader.resource.loader.some_property = some_value
... other properties...
Please note that the configuration properties syntax changed a bit in version 2.1. While the old syntax still works, if you want to avoid deprecation warnings in the log, it's rather:
resource.loaders = .... , my_loader, ...
resource.loader.my_loader.class = com.foo.MyResourceLoader
resource.loader.m_loader.some_property = some_value
... other properties...
The has ResourceLoader interface has four abstract methods that you need to provide:
void init(ExtProperties configuration)
where the configuration
object contains some_property -> some_value
properties pairlong getLastModified(Resource resource)
which returns the number of seconds since a resource has been modifiedReader getResourceReader(String source, String encoding)
to get the actual content of thre resourceboolean isSourceModified(Resource resource)