velocity-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Christoph Reck <Christoph.R...@gmx.net>
Subject Re: Multiple configuration loading in VelocityServlet
Date Tue, 27 Mar 2001 12:27:29 GMT
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

Mime
View raw message