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

java.lang.Object
  extended by javax.servlet.GenericServlet
      extended by javax.servlet.http.HttpServlet
          extended by 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, the servlet will check for a toolbox file at '/WEB-INF/toolbox.xml'.
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 will check for a properties file at '/WEB-INF/velocity.properties'. If no file is found there, then Velocity is initialized with the settings in the classpath at 'org.apache.velocity.tools.view.servlet.velocity.properties'.

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 595092 2007-11-14 22:15:13Z nbubna $
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
protected static java.lang.String DEFAULT_PROPERTIES_PATH
          Default velocity properties file path.
protected static java.lang.String DEFAULT_TOOLBOX_PATH
          Default toolbox configuration file path.
static java.lang.String DEFAULT_TOOLS_PROPERTIES
          Default Runtime properties.
private  java.lang.String defaultContentType
          The default content type.
protected static java.lang.String INIT_PROPS_KEY
          This is the string that is looked for when getInitParameter is called ("org.apache.velocity.properties").
private static long serialVersionUID
          serial version id
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").
protected  ToolboxManager toolboxManager
          A reference to the toolbox manager.
private  org.apache.velocity.app.VelocityEngine velocity
           
private  boolean warnOfOutputStreamDeprecation
          Whether we've logged a deprecation warning for ServletResponse's getOutputStream().
private static org.apache.velocity.util.SimplePool writerPool
          Cache of writers
 
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 e)
          Invoked when there is an error thrown in any part of doRequest() processing.
protected  void fillContext(org.apache.velocity.context.Context context, javax.servlet.http.HttpServletRequest request)
          This is an extension hook for users who subclass this servlet to make their own modifications to the Context.
protected  java.lang.String findInitParameter(javax.servlet.ServletConfig config, java.lang.String key)
          Looks up an init parameter with the specified key in either the ServletConfig or, failing that, in the ServletContext.
protected  java.io.Writer getResponseWriter(javax.servlet.http.HttpServletResponse response)
          Procure a Writer with correct encoding which can be used even if HttpServletResponse's getOutputStream() method has already been called.
protected  org.apache.velocity.Template getTemplate(javax.servlet.http.HttpServletRequest request)
          Gets the requested template.
protected  org.apache.velocity.Template getTemplate(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Gets the requested template.
 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.app.VelocityEngine getVelocityEngine()
          Returns the underlying VelocityEngine being used.
protected  java.lang.String getVelocityProperty(java.lang.String key, java.lang.String alternate)
          Simplifies process of getting a property from VelocityEngine, because the VelocityEngine interface sucks compared to the singleton's.
protected  org.apache.velocity.Template handleRequest(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, org.apache.velocity.context.Context ctx)
          Deprecated. This will be removed in VelocityTools 2.0.
 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 velocityEngine.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.
private  org.apache.commons.collections.ExtendedProperties loadDefaultProperties()
           
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 performMerge(org.apache.velocity.Template template, org.apache.velocity.context.Context context, java.io.Writer writer)
          This is here so developers may override it and gain access to the Writer which the template will be merged into.
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.
protected  void setVelocityEngine(org.apache.velocity.app.VelocityEngine ve)
          Sets the underlying VelocityEngine
 
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

serialVersionUID

private static final long serialVersionUID
serial version id

See Also:
Constant Field Values

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.


DEFAULT_TOOLS_PROPERTIES

public static final java.lang.String DEFAULT_TOOLS_PROPERTIES
Default Runtime properties.

See Also:
Constant Field Values

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

DEFAULT_TOOLBOX_PATH

protected static final java.lang.String DEFAULT_TOOLBOX_PATH
Default toolbox configuration file path. If no alternate value for this is specified, the servlet will look here.

See Also:
Constant Field Values

DEFAULT_PROPERTIES_PATH

protected static final java.lang.String DEFAULT_PROPERTIES_PATH
Default velocity properties file path. If no alternate value for this is specified, the servlet will look here.

See Also:
Constant Field Values

toolboxManager

protected ToolboxManager toolboxManager
A reference to the toolbox manager.


writerPool

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


velocity

private org.apache.velocity.app.VelocityEngine velocity

defaultContentType

private java.lang.String defaultContentType
The default content type. When necessary, includes the character set to use when encoding textual output.


warnOfOutputStreamDeprecation

private boolean warnOfOutputStreamDeprecation
Whether we've logged a deprecation warning for ServletResponse's getOutputStream().

Since:
VelocityTools 1.1
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.

NOTE: If no charset is specified in the default.contentType property (in your velocity.properties) and you have specified an output.encoding property, then that will be used as the charset for the default content-type of pages served by this servlet.

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

findInitParameter

protected java.lang.String findInitParameter(javax.servlet.ServletConfig config,
                                             java.lang.String key)
Looks up an init parameter with the specified key in either the ServletConfig or, failing that, in the ServletContext.


getVelocityProperty

protected java.lang.String getVelocityProperty(java.lang.String key,
                                               java.lang.String alternate)
Simplifies process of getting a property from VelocityEngine, because the VelocityEngine interface sucks compared to the singleton's. Use of this method assumes that initVelocity(ServletConfig) has already been called.


getVelocityEngine

protected org.apache.velocity.app.VelocityEngine getVelocityEngine()
Returns the underlying VelocityEngine being used.


setVelocityEngine

protected void setVelocityEngine(org.apache.velocity.app.VelocityEngine ve)
Sets the underlying VelocityEngine


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
Throws:
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 velocityEngine.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
Throws:
javax.servlet.ServletException

loadDefaultProperties

private org.apache.commons.collections.ExtendedProperties loadDefaultProperties()

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
Throws:
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
Throws:
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
Throws:
javax.servlet.ServletException
java.io.IOException

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
Deprecated. This will be removed in VelocityTools 2.0.

This was a common extension point, but has been deprecated. It has no single replacement. Instead, you should override fillContext(org.apache.velocity.context.Context, javax.servlet.http.HttpServletRequest) to add custom things to the Context or override a getTemplate(javax.servlet.http.HttpServletRequest) method to change how Templates are retrieved

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

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

fillContext

protected void fillContext(org.apache.velocity.context.Context context,
                           javax.servlet.http.HttpServletRequest request)
This is an extension hook for users who subclass this servlet to make their own modifications to the Context. It is a partial replacement of the deprecated handleRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.apache.velocity.context.Context) method. This implementation does nothing.


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

getTemplate

protected org.apache.velocity.Template getTemplate(javax.servlet.http.HttpServletRequest request)
                                            throws org.apache.velocity.exception.ResourceNotFoundException,
                                                   org.apache.velocity.exception.ParseErrorException,
                                                   java.lang.Exception

Gets the requested template.

Parameters:
request - client request
Returns:
Velocity Template object or null
Throws:
org.apache.velocity.exception.ResourceNotFoundException
org.apache.velocity.exception.ParseErrorException
java.lang.Exception

getTemplate

protected org.apache.velocity.Template getTemplate(javax.servlet.http.HttpServletRequest request,
                                                   javax.servlet.http.HttpServletResponse response)
                                            throws org.apache.velocity.exception.ResourceNotFoundException,
                                                   org.apache.velocity.exception.ParseErrorException,
                                                   java.lang.Exception

Gets the requested template.

Parameters:
request - client request
response - client response (whose character encoding we'll use)
Returns:
Velocity Template object or null
Throws:
org.apache.velocity.exception.ResourceNotFoundException
org.apache.velocity.exception.ParseErrorException
java.lang.Exception

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(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
response - servlet reponse (used to get a Writer)
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

performMerge

protected void performMerge(org.apache.velocity.Template template,
                            org.apache.velocity.context.Context context,
                            java.io.Writer writer)
                     throws org.apache.velocity.exception.ResourceNotFoundException,
                            org.apache.velocity.exception.ParseErrorException,
                            org.apache.velocity.exception.MethodInvocationException,
                            java.lang.Exception
This is here so developers may override it and gain access to the Writer which the template will be merged into. See VELTOOLS-7 for discussion of this.

Parameters:
template - template object returned by the handleRequest() method
context - Context created by the createContext(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
writer - a VelocityWriter that the template is merged into
Throws:
org.apache.velocity.exception.ResourceNotFoundException
org.apache.velocity.exception.ParseErrorException
org.apache.velocity.exception.MethodInvocationException
java.lang.Exception

error

protected void error(javax.servlet.http.HttpServletRequest request,
                     javax.servlet.http.HttpServletResponse response,
                     java.lang.Exception e)
              throws javax.servlet.ServletException
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.
e - Exception that was thrown by some other part of process.
Throws:
javax.servlet.ServletException

getResponseWriter

protected java.io.Writer getResponseWriter(javax.servlet.http.HttpServletResponse response)
                                    throws java.io.UnsupportedEncodingException,
                                           java.io.IOException

Procure a Writer with correct encoding which can be used even if HttpServletResponse's getOutputStream() method has already been called.

This is a transitional method which will be removed in a future version of Velocity. It is not recommended that you override this method.

Parameters:
response - The response.
Returns:
A Writer, possibly created using the getOutputStream().
Throws:
java.io.UnsupportedEncodingException
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. This default implementation does nothing.

Parameters:
request - servlet request from client
response - servlet reponse
context - Context created by the createContext(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)


Copyright (c) 2003-2007 Apache Software Foundation