org.apache.velocity.tools.view.servlet
Class VelocityViewServlet

java.lang.Object
  |
  +--javax.servlet.GenericServlet
        |
        +--javax.servlet.http.HttpServlet
              |
              +--org.apache.velocity.tools.view.servlet.VelocityViewServlet
All Implemented Interfaces:
java.io.Serializable, javax.servlet.Servlet, javax.servlet.ServletConfig
Direct Known Subclasses:
VelocityLayoutServlet

public class VelocityViewServlet
extends javax.servlet.http.HttpServlet

A servlet to process Velocity templates. This is comparable to the the JspServlet for JSP-based applications.

The servlet provides the following features:

VelocityViewServlet supports the following configuration parameters in web.xml:

org.apache.velocity.toolbox
Path and name of the toolbox configuration file. The path must be relative to the web application root directory. If this parameter is not found, no toolbox is instantiated.
org.apache.velocity.properties
Path and name of the Velocity configuration file. The path must be relative to the web application root directory. If this parameter is not present, Velocity is initialized with default settings.

There are methods you may wish to override to access, alter or control any part of the request processing chain. Please see the javadocs for more information on :

Version:
$Id: VelocityViewServlet.java,v 1.10 2003/05/28 00:17:16 nbubna Exp $
Author:
Dave Bryson, Jon S. Stevens, Gabe Sidler, Geir Magnusson Jr., Kent Johnson, Daniel Rall, Nathan Bubna
See Also:
Serialized Form

Field Summary
static java.lang.String CONTENT_TYPE
          The HTTP content type context key.
static java.lang.String DEFAULT_CONTENT_TYPE
          The default content type for the response
static java.lang.String DEFAULT_OUTPUT_ENCODING
          Default encoding for the output stream
private  java.lang.String defaultContentType
          The default content type.
private  java.lang.String encoding
          The encoding to use when generating outputing.
protected static java.lang.String INIT_PROPS_KEY
          This is the string that is looked for when getInitParameter is called ("org.apache.velocity.properties").
static java.lang.String SERVLET_CONTEXT_KEY
          Key used to access the ServletContext in the Velocity application attributes.
protected static java.lang.String TOOLBOX_KEY
          Key used to access the toolbox configuration file path from the Servlet or webapp init parameters ("org.apache.velocity.toolbox").
private  ServletToolboxManager toolboxManager
          A reference to the toolbox manager.
private static org.apache.velocity.util.SimplePool writerPool
          Cache of writers
 
Fields inherited from class javax.servlet.http.HttpServlet
 
Fields inherited from class javax.servlet.GenericServlet
 
Constructor Summary
VelocityViewServlet()
           
 
Method Summary
protected  org.apache.velocity.context.Context createContext(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Creates and returns an initialized Velocity context.
 void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Handles GET - calls doRequest()
 void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Handle a POST request - calls doRequest()
protected  void doRequest(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Handles with both GET and POST requests
protected  void error(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.Exception cause)
          Invoked when there is an error thrown in any part of doRequest() processing.
 org.apache.velocity.Template getTemplate(java.lang.String name)
          Retrieves the requested template.
 org.apache.velocity.Template getTemplate(java.lang.String name, java.lang.String encoding)
          Retrieves the requested template with the specified character encoding.
protected  org.apache.velocity.Template handleRequest(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, org.apache.velocity.context.Context ctx)
          Handle the template processing request.
 void init(javax.servlet.ServletConfig config)
          Initializes servlet, toolbox and Velocity template engine.
protected  void initToolbox(javax.servlet.ServletConfig config)
          Initializes the ServletToolboxManager for this servlet's toolbox (if any).
protected  void initVelocity(javax.servlet.ServletConfig config)
          Initializes the Velocity runtime, first calling loadConfiguration(ServletConfig) to get a org.apache.commons.collections.ExtendedProperties of configuration information and then calling Velocity.init().
protected  org.apache.commons.collections.ExtendedProperties loadConfiguration(javax.servlet.ServletConfig config)
          Loads the configuration information and returns that information as an ExtendedProperties, which will be used to initialize the Velocity runtime.
protected  void mergeTemplate(org.apache.velocity.Template template, org.apache.velocity.context.Context context, javax.servlet.http.HttpServletResponse response)
          merges the template with the context.
protected  void requestCleanup(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, org.apache.velocity.context.Context context)
          cleanup routine called at the end of the request processing sequence allows a derived class to do resource cleanup or other end of process cycle tasks
protected  void setContentType(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Sets the content type of the response.
 
Methods inherited from class javax.servlet.http.HttpServlet
doDelete, doHead, doOptions, doPut, doTrace, getLastModified, service, service
 
Methods inherited from class javax.servlet.GenericServlet
destroy, getInitParameter, getInitParameterNames, getServletConfig, getServletContext, getServletInfo, getServletName, init, log, log
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

CONTENT_TYPE

public static final java.lang.String CONTENT_TYPE
The HTTP content type context key.

See Also:
Constant Field Values

DEFAULT_CONTENT_TYPE

public static final java.lang.String DEFAULT_CONTENT_TYPE
The default content type for the response

See Also:
Constant Field Values

DEFAULT_OUTPUT_ENCODING

public static final java.lang.String DEFAULT_OUTPUT_ENCODING
Default encoding for the output stream

See Also:
Constant Field Values

SERVLET_CONTEXT_KEY

public static final java.lang.String SERVLET_CONTEXT_KEY
Key used to access the ServletContext in the Velocity application attributes.


TOOLBOX_KEY

protected static final java.lang.String TOOLBOX_KEY
Key used to access the toolbox configuration file path from the Servlet or webapp init parameters ("org.apache.velocity.toolbox").

See Also:
Constant Field Values

INIT_PROPS_KEY

protected static final java.lang.String INIT_PROPS_KEY
This is the string that is looked for when getInitParameter is called ("org.apache.velocity.properties").

See Also:
Constant Field Values

writerPool

private static org.apache.velocity.util.SimplePool writerPool
Cache of writers


encoding

private java.lang.String encoding
The encoding to use when generating outputing.


defaultContentType

private java.lang.String defaultContentType
The default content type.


toolboxManager

private ServletToolboxManager toolboxManager
A reference to the toolbox manager.

Constructor Detail

VelocityViewServlet

public VelocityViewServlet()
Method Detail

init

public void init(javax.servlet.ServletConfig config)
          throws javax.servlet.ServletException

Initializes servlet, toolbox and Velocity template engine. Called by the servlet container on loading.

Specified by:
init in interface javax.servlet.Servlet
Overrides:
init in class javax.servlet.GenericServlet
Parameters:
config - servlet configuation
javax.servlet.ServletException

initToolbox

protected void initToolbox(javax.servlet.ServletConfig config)
                    throws javax.servlet.ServletException
Initializes the ServletToolboxManager for this servlet's toolbox (if any).

Parameters:
config - servlet configuation
javax.servlet.ServletException

initVelocity

protected void initVelocity(javax.servlet.ServletConfig config)
                     throws javax.servlet.ServletException
Initializes the Velocity runtime, first calling loadConfiguration(ServletConfig) to get a org.apache.commons.collections.ExtendedProperties of configuration information and then calling Velocity.init(). Override this to do anything to the environment before the initialization of the singleton takes place, or to initialize the singleton in other ways.

Parameters:
config - servlet configuration parameters
javax.servlet.ServletException

loadConfiguration

protected org.apache.commons.collections.ExtendedProperties loadConfiguration(javax.servlet.ServletConfig config)
                                                                       throws java.io.IOException
Loads the configuration information and returns that information as an ExtendedProperties, which will be used to initialize the Velocity runtime.

Currently, this method gets the initialization parameter VelocityServlet.INIT_PROPS_KEY, which should be a file containing the configuration information.

To configure your Servlet Spec 2.2 compliant servlet runner to pass this to you, put the following in your WEB-INF/web.xml file
    <servlet>
      <servlet-name> YourServlet </servlet-name>
      <servlet-class> your.package.YourServlet </servlet-class>
      <init-param>
         <param-name> org.apache.velocity.properties </param-name>
         <param-value> velocity.properties </param-value>
      </init-param>
    </servlet>
   
Alternately, if you wish to configure an entire context in this fashion, you may use the following:
    <context-param>
       <param-name> org.apache.velocity.properties </param-name>
       <param-value> velocity.properties </param-value>
       <description> Path to Velocity configuration </description>
    </context-param>
   
Derived classes may do the same, or take advantage of this code to do the loading for them via :
      ExtendedProperties p = super.loadConfiguration(config);
   
and then add or modify the configuration values from the file.

Parameters:
config - ServletConfig passed to the servlets init() function Can be used to access the real path via ServletContext (hint)
Returns:
ExtendedProperties loaded with configuration values to be used to initialize the Velocity runtime.
Throws:
java.io.IOException - I/O problem accessing the specified file, if specified.

doGet

public void doGet(javax.servlet.http.HttpServletRequest request,
                  javax.servlet.http.HttpServletResponse response)
           throws javax.servlet.ServletException,
                  java.io.IOException
Handles GET - calls doRequest()

Overrides:
doGet in class javax.servlet.http.HttpServlet
javax.servlet.ServletException
java.io.IOException

doPost

public void doPost(javax.servlet.http.HttpServletRequest request,
                   javax.servlet.http.HttpServletResponse response)
            throws javax.servlet.ServletException,
                   java.io.IOException
Handle a POST request - calls doRequest()

Overrides:
doPost in class javax.servlet.http.HttpServlet
javax.servlet.ServletException
java.io.IOException

doRequest

protected void doRequest(javax.servlet.http.HttpServletRequest request,
                         javax.servlet.http.HttpServletResponse response)
                  throws javax.servlet.ServletException,
                         java.io.IOException
Handles with both GET and POST requests

Parameters:
request - HttpServletRequest object containing client request
response - HttpServletResponse object for the response
javax.servlet.ServletException
java.io.IOException

requestCleanup

protected void requestCleanup(javax.servlet.http.HttpServletRequest request,
                              javax.servlet.http.HttpServletResponse response,
                              org.apache.velocity.context.Context context)
cleanup routine called at the end of the request processing sequence allows a derived class to do resource cleanup or other end of process cycle tasks

Parameters:
request - servlet request from client
response - servlet reponse
context - context created by the createContext() method

handleRequest

protected org.apache.velocity.Template handleRequest(javax.servlet.http.HttpServletRequest request,
                                                     javax.servlet.http.HttpServletResponse response,
                                                     org.apache.velocity.context.Context ctx)
                                              throws java.lang.Exception

Handle the template processing request.

Parameters:
request - client request
response - client response
ctx - VelocityContext to fill
Returns:
Velocity Template object or null
java.lang.Exception

setContentType

protected void setContentType(javax.servlet.http.HttpServletRequest request,
                              javax.servlet.http.HttpServletResponse response)
Sets the content type of the response. This is available to be overriden by a derived class.

The default implementation is :


     response.setContentType(defaultContentType);
 
  
where defaultContentType is set to the value of the default.contentType property, or "text/html" if that is not set.

Parameters:
request - servlet request from client
response - servlet reponse to client

createContext

protected org.apache.velocity.context.Context createContext(javax.servlet.http.HttpServletRequest request,
                                                            javax.servlet.http.HttpServletResponse response)

Creates and returns an initialized Velocity context.

A new context of class ChainedContext is created and initialized.

Parameters:
request - servlet request from client
response - servlet reponse to client

getTemplate

public org.apache.velocity.Template getTemplate(java.lang.String name)
                                         throws org.apache.velocity.exception.ResourceNotFoundException,
                                                org.apache.velocity.exception.ParseErrorException,
                                                java.lang.Exception
Retrieves the requested template.

Parameters:
name - The file name of the template to retrieve relative to the template root.
Returns:
The requested template.
Throws:
org.apache.velocity.exception.ResourceNotFoundException - if template not found from any available source.
org.apache.velocity.exception.ParseErrorException - if template cannot be parsed due to syntax (or other) error.
java.lang.Exception - if an error occurs in template initialization

getTemplate

public org.apache.velocity.Template getTemplate(java.lang.String name,
                                                java.lang.String encoding)
                                         throws org.apache.velocity.exception.ResourceNotFoundException,
                                                org.apache.velocity.exception.ParseErrorException,
                                                java.lang.Exception
Retrieves the requested template with the specified character encoding.

Parameters:
name - The file name of the template to retrieve relative to the template root.
encoding - the character encoding of the template
Returns:
The requested template.
Throws:
org.apache.velocity.exception.ResourceNotFoundException - if template not found from any available source.
org.apache.velocity.exception.ParseErrorException - if template cannot be parsed due to syntax (or other) error.
java.lang.Exception - if an error occurs in template initialization

mergeTemplate

protected void mergeTemplate(org.apache.velocity.Template template,
                             org.apache.velocity.context.Context context,
                             javax.servlet.http.HttpServletResponse response)
                      throws org.apache.velocity.exception.ResourceNotFoundException,
                             org.apache.velocity.exception.ParseErrorException,
                             org.apache.velocity.exception.MethodInvocationException,
                             java.io.IOException,
                             java.io.UnsupportedEncodingException,
                             java.lang.Exception
merges the template with the context. Only override this if you really, really really need to. (And don't call us with questions if it breaks :)

Parameters:
template - template object returned by the handleRequest() method
context - context created by the createContext() method
response - servlet reponse (use this to get the output stream or Writer
org.apache.velocity.exception.ResourceNotFoundException
org.apache.velocity.exception.ParseErrorException
org.apache.velocity.exception.MethodInvocationException
java.io.IOException
java.io.UnsupportedEncodingException
java.lang.Exception

error

protected void error(javax.servlet.http.HttpServletRequest request,
                     javax.servlet.http.HttpServletResponse response,
                     java.lang.Exception cause)
              throws javax.servlet.ServletException,
                     java.io.IOException
Invoked when there is an error thrown in any part of doRequest() processing.

Default will send a simple HTML response indicating there was a problem.

Parameters:
request - original HttpServletRequest from servlet container.
response - HttpServletResponse object from servlet container.
cause - Exception that was thrown by some other part of process.
javax.servlet.ServletException
java.io.IOException


Copyright (c) 2003 Apache Software Foundation