You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@velocity.apache.org by Thomas Fahrmeyer <th...@einsurance.de> on 2001/03/26 14:25:48 UTC
Multiple configuration loading in VelocityServlet
Any of my servlets rendering the template is a subclass of VelocityServlet.
Each time a new instance is created the init(config) of Velocity is called.
That's ok. But the code is ...
try
{
/*
* call the overridable method to allow the
* derived classes a shot at altering the configuration
* before initializing Runtime
*/
Properties props = loadConfiguration( config );
Velocity.init( props );
defaultContentType = DEFAULT_CONTENT_TYPE;
encoding = Runtime.getString(Runtime.TEMPLATE_ENCODING,
"8859_1");
}
catch( Exception e )
{
throw new ServletException("Error configuring the loader: " +
e);
}
... and the property file is loaded every time. I think that can be avoided
;) Or is there an idea behind that ?
bye
Thomas
Re: Multiple configuration loading in VelocityServlet
Posted by Christoph Reck <Ch...@gmx.net>.
I have sovled this in a nicer way... There is only one VelocityServlet
subclass, which preloaded and saves its instance during init(), retrievable
via a static getInstance() method. Since there are no globals (other than
a pre-initialized global context) in my servlet, I have:
/**
* Generate the page output using the template engine.
*
* @param request The HttpServletRequest.
* @param response The HttpServletResponse.
* @param out The output PrintWriter.
* @param map The key=value map to add to the template context.
*
* @return This method has no return value.
**/
public static void process( HttpServletRequest request,
HttpServletResponse response,
PrintWriter out,
Map map )
throws Exception
{
TemplateServlet templateEngine = TemplateServlet.getInstance();
Context context = templateEngine.prepareContext(request, response);
// Add passed data to the context
for(Iterator i = map.keySet().iterator(); i.hasNext(); )
{
String key = (String) i.next();
context.put( key, map.get(key) );
}
// render the output
Template template = templateEngine.handleRequest(context);
String contentType = (String) context.get(templateEngine.CONTENT_TYPE);
response.setContentType(contentType);
template.merge(context, out);
}
Now I just can call the engine from any other servlet and profit from the
VelocityServlet caching, pooling, etc...
NOTES:
* The out parameter may be gotten directly from the response, but I've
heard of some servlet container implementations that refuse to allow
response.getOutput() a second time. If your Servlets do not use the
output stream previously, you can optimize away the out parameter.
* The copying of the Map may be avoided by creating a special Context
implementation
Hope this idea helps.
:) Chirstoph