org.apache.velocity.servlet
Class VelocityServlet

java.lang.Object
  |
  +--javax.servlet.GenericServlet
        |
        +--javax.servlet.http.HttpServlet
              |
              +--org.apache.velocity.servlet.VelocityServlet
All Implemented Interfaces:
java.io.Serializable, javax.servlet.Servlet, javax.servlet.ServletConfig

public abstract class VelocityServlet
extends javax.servlet.http.HttpServlet

Base class which simplifies the use of Velocity with Servlets. Extend this class, implement the handleRequest() method, and add your data to the context. Then call getTemplate("myTemplate.wm"). This class puts some things into the context object that you should be aware of:

 "req" - The HttpServletRequest object
 "res" - The HttpServletResponse object
 
There are other methods you can override to access, alter or control any part of the request processing chain. Please see the javadocs for more information on :
If you put a contentType object into the context within either your serlvet or within your template, then that will be used to override the default content type specified in the properties file. "contentType" - The value for the Content-Type: header

Author:
Dave Bryson, Jon S. Stevens, Geir Magnusson Jr., Kent Johnson $Id: VelocityServlet.java,v 1.44 2002/02/06 23:42:01 dlr Exp $
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
          Encoding for the output stream
private static java.lang.String defaultContentType
          The default content type.
private static 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.
static java.lang.String REQUEST
          The HTTP request object context key.
static java.lang.String RESPONSE
          The HTTP response object context key.
private static SimplePool writerPool
          Cache of writers
 
Fields inherited from class javax.servlet.http.HttpServlet
HEADER_IFMODSINCE, HEADER_LASTMOD, LSTRING_FILE, lStrings, METHOD_DELETE, METHOD_GET, METHOD_HEAD, METHOD_OPTIONS, METHOD_POST, METHOD_PUT, METHOD_TRACE
 
Fields inherited from class javax.servlet.GenericServlet
config
 
Constructor Summary
VelocityServlet()
           
 
Method Summary
protected  Context createContext(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Returns a context suitable to pass to the handleRequest() method

Default implementation will create a VelocityContext object, put the HttpServletRequest and HttpServletResponse into the context accessable via the keys VelocityServlet.REQUEST and VelocityServlet.RESPONSE, respectively.
 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 all 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.
 Template getTemplate(java.lang.String name)
          Retrieves the requested template.
 Template getTemplate(java.lang.String name, java.lang.String encoding)
          Retrieves the requested template with the specified character encoding.
protected  Template handleRequest(Context ctx)
          Deprecated. Use handleRequest( HttpServletRequest request, HttpServletResponse response, Context ctx )
protected  Template handleRequest(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Context ctx)
          Implement this method to add your application data to the context, calling the getTemplate() method to produce your return value.
 void init(javax.servlet.ServletConfig config)
          Performs initialization of this servlet.
protected  void initVelocity(javax.servlet.ServletConfig config)
          Initializes the Velocity runtime, first calling loadConfiguration(ServletConvig) to get a java.util.Properties of configuration information and then calling Velocity.init().
protected  java.util.Properties loadConfiguration(javax.servlet.ServletConfig config)
          Loads the configuration information and returns that information as a Properties, which will be used to initialize the Velocity runtime.
protected  void mergeTemplate(Template template, 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, 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, getAllDeclaredMethods, getLastModified, maybeSetLastModified, 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, registerNatives, toString, wait, wait, wait
 

Field Detail

REQUEST

public static final java.lang.String REQUEST
The HTTP request object context key.

RESPONSE

public static final java.lang.String RESPONSE
The HTTP response object context key.

CONTENT_TYPE

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

DEFAULT_CONTENT_TYPE

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

DEFAULT_OUTPUT_ENCODING

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

encoding

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

defaultContentType

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

INIT_PROPS_KEY

protected static final java.lang.String INIT_PROPS_KEY
This is the string that is looked for when getInitParameter is called.

writerPool

private static SimplePool writerPool
Cache of writers
Constructor Detail

VelocityServlet

public VelocityServlet()
Method Detail

init

public void init(javax.servlet.ServletConfig config)
          throws javax.servlet.ServletException
Performs initialization of this servlet. Called by the servlet container on loading.
Overrides:
init in class javax.servlet.GenericServlet
Parameters:
config - The servlet configuration to apply.
Throws:
javax.servlet.ServletException -  

initVelocity

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

loadConfiguration

protected java.util.Properties loadConfiguration(javax.servlet.ServletConfig config)
                                          throws java.io.IOException,
                                                 java.io.FileNotFoundException
Loads the configuration information and returns that information as a Properties, 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> 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> 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 :
      Properties 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:
java.util.Properties loaded with configuration values to be used to initialize the Velocity runtime.
Throws:
java.io.FileNotFoundException - if a specified file is not found.
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

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

doRequest

protected void doRequest(javax.servlet.http.HttpServletRequest request,
                         javax.servlet.http.HttpServletResponse response)
                  throws javax.servlet.ServletException,
                         java.io.IOException
Handles all requests
Parameters:
request - HttpServletRequest object containing client request
response - HttpServletResponse object for the response

requestCleanup

protected void requestCleanup(javax.servlet.http.HttpServletRequest request,
                              javax.servlet.http.HttpServletResponse response,
                              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

mergeTemplate

protected void mergeTemplate(Template template,
                             Context context,
                             javax.servlet.http.HttpServletResponse response)
                      throws ResourceNotFoundException,
                             ParseErrorException,
                             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

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 Context createContext(javax.servlet.http.HttpServletRequest request,
                                javax.servlet.http.HttpServletResponse response)
Returns a context suitable to pass to the handleRequest() method

Default implementation will create a VelocityContext object, put the HttpServletRequest and HttpServletResponse into the context accessable via the keys VelocityServlet.REQUEST and VelocityServlet.RESPONSE, respectively.
Parameters:
request - servlet request from client
response - servlet reponse to client
Returns:
context

getTemplate

public Template getTemplate(java.lang.String name)
                     throws ResourceNotFoundException,
                            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:
ResourceNotFoundException - if template not found from any available source.
ParseErrorException - if template cannot be parsed due to syntax (or other) error.
java.lang.Exception - if an error occurs in template initialization

getTemplate

public Template getTemplate(java.lang.String name,
                            java.lang.String encoding)
                     throws ResourceNotFoundException,
                            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:
ResourceNotFoundException - if template not found from any available source.
ParseErrorException - if template cannot be parsed due to syntax (or other) error.
java.lang.Exception - if an error occurs in template initialization
Since:
Velocity v1.1

handleRequest

protected Template handleRequest(javax.servlet.http.HttpServletRequest request,
                                 javax.servlet.http.HttpServletResponse response,
                                 Context ctx)
                          throws java.lang.Exception
Implement this method to add your application data to the context, calling the getTemplate() method to produce your return value.

In the event of a problem, you may handle the request directly and return null or throw a more meaningful exception for the error handler to catch.
Parameters:
request - servlet request from client
response - servlet reponse
ctx - The context to add your data to.
Returns:
The template to merge with your context or null, indicating that you handled the processing.
Since:
Velocity v1.1

handleRequest

protected Template handleRequest(Context ctx)
                          throws java.lang.Exception
Deprecated. Use handleRequest( HttpServletRequest request, HttpServletResponse response, Context ctx )

Implement this method to add your application data to the context, calling the getTemplate() method to produce your return value.

In the event of a problem, you may simple return null or throw a more meaningful exception.
Parameters:
ctx - The context to add your data to.
Returns:
The template to merge with your context.

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.


Copyright © 2003 Apache Software Foundation. All Rights Reserved.