com.samskivert.velocity
Class DispatcherServlet

java.lang.Object
  extended by javax.servlet.GenericServlet
      extended by javax.servlet.http.HttpServlet
          extended by com.samskivert.velocity.DispatcherServlet
All Implemented Interfaces:
Serializable, javax.servlet.Servlet, javax.servlet.ServletConfig, org.apache.velocity.app.event.EventHandler, org.apache.velocity.app.event.MethodExceptionEventHandler

public class DispatcherServlet
extends javax.servlet.http.HttpServlet
implements org.apache.velocity.app.event.MethodExceptionEventHandler

The dispatcher servlet builds upon Velocity's architecture. It does so in the following ways:

URI to servlet mapping
The mapping process allows the Velocity framework to be invoked for all requests ending in a particular file extension (usually .wm). It is necessary to instruct your servlet engine of choice to invoke the DispatcherServlet for all requests ending in that extension. For Apache/JServ this looks something like this:

 ApJServAction .wm /servlets/com.samskivert.velocity.Dispatcher
 
The request URI then defines the path of the template that will be used to satisfy the request. To understand how code is selected to go along with the request, let's look at an example. Consider the following configuration:
 applications=whowhere
 whowhere.base_uri=/whowhere
 whowhere.base_pkg=whowhere.logic
 
This defines an application identified as whowhere. An application is defined by three parameters, the application identifier, the base_uri, and the base_pkg. The base_uri defines the prefix shared by all pages served by the application and which serves to identify which application to invoke when processing a request. The base_pkg is used to construct the logic classname based on the URI and the base_uri parameter.

Now let's look at a sample request to determine how the logic classname is resolved. Consider the following request URI:

 /whowhere/view/trips.wm
 
It begins with /whowhere which tells the dispatcher that it's part of the whowhere application. That application's base_uri is then stripped from the URI leaving /view/trips.wm. The slashes are converted into periods to map directories to packages, giving us view.trips.wm. Finally, the base_pkg is prepended and the trailing .wm extension removed.

Thus the class invoked to populate the context for this request is whowhere.servlets.view.trips (note that the classname is lowercase which is an intentional choice in resolving conflicting recommendations that classnames should always start with a capital letter and URLs should always be lowercase).

The template used to generate the result is loaded based on the full URI, essentially with a call to getTemplate("/whowhere/view/trips.wm") in this example. This is the place where more sophisticated cobranding support could be inserted in the future (ie. if I ever want to use this to develop a cobranded web site).

See Also:
Logic, Serialized Form

Field Summary
protected  Application _app
          The application being served by this dispatcher servlet.
protected  String _charset
          The character set in which serve our responses.
protected  String _defaultContentType
          Our default content type.
protected  HashMap<String,Logic> _logic
          A table of resolved logic instances.
protected  boolean _usingSiteLoading
          Set to true if we're using the SiteResourceLoader.
protected static org.apache.velocity.util.SimplePool _writerPool
          A pool of VelocityWriter instances.
protected static String APP_CLASS_KEY
          The servlet parameter key specifying the application class.
protected static String APPLICATION_KEY
          This is the key used to store a reference back to the dispatcher servlet in our invocation context.
protected static String CHARSET_KEY
          The servlet parameter key specifying the default character set.
static String CONTENT_TYPE
          The HTTP content type context key.
protected static String CURRENCYTOOL_KEY
          The key used to store the currency tool in the context.
protected static String DATATOOL_KEY
          The key used to store the data tool in the context.
protected static String DEFAULT_CONTENT_TYPE
          The default content type for responses.
protected static String DEFAULT_OUTPUT_ENCODING
          The default encoding for the output stream.
protected static String ERROR_KEY
          This is the key used in the context for error messages.
protected static String FORMTOOL_KEY
          The key used to store the form tool in the context.
protected static String I18NTOOL_KEY
          The key used to store the translation tool in the context.
protected static String INIT_PROPS_KEY
          Describes the location of our properties.
protected static String LOGIC_PKG_KEY
          The servlet parameter key specifying the base logic package.
protected static String STRINGTOOL_KEY
          The key used to store the string tool in the context.
 
Constructor Summary
DispatcherServlet()
           
 
Method Summary
protected  String chooseCharacterEncoding(javax.servlet.http.HttpServletRequest request)
          Chooses the output character encoding to be used as the value for the "charset=" portion of the HTTP Content-Type header (and thus returned by response.getCharacterEncoding()).
 void destroy()
          Clean up after ourselves and our application.
 void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Handles HTTP GET requests by calling #doRequest().
 void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Handles HTTP POST requests by calling #doRequest().
protected  void doRequest(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Handles all requests (by default).
static Application getApplication(InvocationContext context)
          Returns the reference to the application that is handling this request.
 org.apache.velocity.Template handleRequest(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse rsp, org.apache.velocity.context.Context ctx)
          Loads up the template appropriate for this request, locates and invokes any associated logic class and finally returns the prepared template which will be merged with the prepared context.
 void init(javax.servlet.ServletConfig config)
           
protected  Properties loadConfiguration(javax.servlet.ServletConfig config)
          We load our velocity properties from the classpath rather than from a file.
protected  void mergeTemplate(org.apache.velocity.Template template, InvocationContext context)
          Merges the template with the context.
 Object methodException(Class clazz, String method, Exception e)
          Called when a method throws an exception during template evaluation.
protected  Logic resolveLogic(String path)
          This method is called to select the appropriate logic for this request URI.
protected  org.apache.velocity.Template selectTemplate(int siteId, InvocationContext ctx)
          This method is called to select the appropriate template for this request.
protected  void setContentType(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Sets the content type of the response, defaulting to #defaultContentType if not overriden.
 
Methods inherited from class javax.servlet.http.HttpServlet
doDelete, doHead, doOptions, doPut, doTrace, getLastModified, service, service
 
Methods inherited from class javax.servlet.GenericServlet
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 String CONTENT_TYPE
The HTTP content type context key.

See Also:
Constant Field Values

_app

protected Application _app
The application being served by this dispatcher servlet.


_logic

protected HashMap<String,Logic> _logic
A table of resolved logic instances.


_charset

protected String _charset
The character set in which serve our responses.


_usingSiteLoading

protected boolean _usingSiteLoading
Set to true if we're using the SiteResourceLoader.


_defaultContentType

protected String _defaultContentType
Our default content type.


_writerPool

protected static org.apache.velocity.util.SimplePool _writerPool
A pool of VelocityWriter instances.


INIT_PROPS_KEY

protected static final String INIT_PROPS_KEY
Describes the location of our properties.

See Also:
Constant Field Values

ERROR_KEY

protected static final String ERROR_KEY
This is the key used in the context for error messages.

See Also:
Constant Field Values

APPLICATION_KEY

protected static final String APPLICATION_KEY
This is the key used to store a reference back to the dispatcher servlet in our invocation context.

See Also:
Constant Field Values

I18NTOOL_KEY

protected static final String I18NTOOL_KEY
The key used to store the translation tool in the context.

See Also:
Constant Field Values

FORMTOOL_KEY

protected static final String FORMTOOL_KEY
The key used to store the form tool in the context.

See Also:
Constant Field Values

STRINGTOOL_KEY

protected static final String STRINGTOOL_KEY
The key used to store the string tool in the context.

See Also:
Constant Field Values

DATATOOL_KEY

protected static final String DATATOOL_KEY
The key used to store the data tool in the context.

See Also:
Constant Field Values

CURRENCYTOOL_KEY

protected static final String CURRENCYTOOL_KEY
The key used to store the currency tool in the context.

See Also:
Constant Field Values

APP_CLASS_KEY

protected static final String APP_CLASS_KEY
The servlet parameter key specifying the application class.

See Also:
Constant Field Values

LOGIC_PKG_KEY

protected static final String LOGIC_PKG_KEY
The servlet parameter key specifying the base logic package.

See Also:
Constant Field Values

CHARSET_KEY

protected static final String CHARSET_KEY
The servlet parameter key specifying the default character set.

See Also:
Constant Field Values

DEFAULT_CONTENT_TYPE

protected static final String DEFAULT_CONTENT_TYPE
The default content type for responses.

See Also:
Constant Field Values

DEFAULT_OUTPUT_ENCODING

protected static final String DEFAULT_OUTPUT_ENCODING
The default encoding for the output stream.

See Also:
Constant Field Values
Constructor Detail

DispatcherServlet

public DispatcherServlet()
Method Detail

init

public void init(javax.servlet.ServletConfig config)
          throws javax.servlet.ServletException
Specified by:
init in interface javax.servlet.Servlet
Overrides:
init in class javax.servlet.GenericServlet
Throws:
javax.servlet.ServletException

doGet

public void doGet(javax.servlet.http.HttpServletRequest request,
                  javax.servlet.http.HttpServletResponse response)
           throws javax.servlet.ServletException,
                  IOException
Handles HTTP GET requests by calling #doRequest().

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

doPost

public void doPost(javax.servlet.http.HttpServletRequest request,
                   javax.servlet.http.HttpServletResponse response)
            throws javax.servlet.ServletException,
                   IOException
Handles HTTP POST requests by calling #doRequest().

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

destroy

public void destroy()
Clean up after ourselves and our application.

Specified by:
destroy in interface javax.servlet.Servlet
Overrides:
destroy in class javax.servlet.GenericServlet

loadConfiguration

protected Properties loadConfiguration(javax.servlet.ServletConfig config)
                                throws IOException
We load our velocity properties from the classpath rather than from a file.

Throws:
IOException

handleRequest

public org.apache.velocity.Template handleRequest(javax.servlet.http.HttpServletRequest req,
                                                  javax.servlet.http.HttpServletResponse rsp,
                                                  org.apache.velocity.context.Context ctx)
                                           throws Exception
Loads up the template appropriate for this request, locates and invokes any associated logic class and finally returns the prepared template which will be merged with the prepared context.

Throws:
Exception

methodException

public Object methodException(Class clazz,
                              String method,
                              Exception e)
                       throws Exception
Called when a method throws an exception during template evaluation.

Specified by:
methodException in interface org.apache.velocity.app.event.MethodExceptionEventHandler
Throws:
Exception

getApplication

public static Application getApplication(InvocationContext context)
Returns the reference to the application that is handling this request.

Returns:
The application in effect for this request or null if no application was selected to handle the request.

doRequest

protected void doRequest(javax.servlet.http.HttpServletRequest request,
                         javax.servlet.http.HttpServletResponse response)
                  throws javax.servlet.ServletException,
                         IOException
Handles all requests (by default).

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

setContentType

protected void setContentType(javax.servlet.http.HttpServletRequest request,
                              javax.servlet.http.HttpServletResponse response)
Sets the content type of the response, defaulting to #defaultContentType if not overriden. Delegates to chooseCharacterEncoding(HttpServletRequest) to select the appropriate character encoding.


chooseCharacterEncoding

protected String chooseCharacterEncoding(javax.servlet.http.HttpServletRequest request)
Chooses the output character encoding to be used as the value for the "charset=" portion of the HTTP Content-Type header (and thus returned by response.getCharacterEncoding()). Called by setContentType(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) if an encoding isn't already specified by Content-Type. By default, chooses the value of RuntimeSingleton's output.encoding property.


selectTemplate

protected org.apache.velocity.Template selectTemplate(int siteId,
                                                      InvocationContext ctx)
                                               throws org.apache.velocity.exception.ResourceNotFoundException,
                                                      org.apache.velocity.exception.ParseErrorException,
                                                      Exception
This method is called to select the appropriate template for this request. The default implementation simply loads the template using Velocity's default template loading services based on the URI provided in the request.

Parameters:
ctx - The context of this request.
Returns:
The template to be used in generating the response.
Throws:
org.apache.velocity.exception.ResourceNotFoundException
org.apache.velocity.exception.ParseErrorException
Exception

mergeTemplate

protected void mergeTemplate(org.apache.velocity.Template template,
                             InvocationContext context)
                      throws org.apache.velocity.exception.ResourceNotFoundException,
                             org.apache.velocity.exception.ParseErrorException,
                             org.apache.velocity.exception.MethodInvocationException,
                             UnsupportedEncodingException,
                             IOException,
                             Exception
Merges the template with the context.

Parameters:
template - template object returned by the handleRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.apache.velocity.context.Context) method.
context - context created by the #createContext method.
Throws:
org.apache.velocity.exception.ResourceNotFoundException
org.apache.velocity.exception.ParseErrorException
org.apache.velocity.exception.MethodInvocationException
UnsupportedEncodingException
IOException
Exception

resolveLogic

protected Logic resolveLogic(String path)
This method is called to select the appropriate logic for this request URI.

Returns:
The logic to be used in generating the response or null if no logic could be matched.


Copyright © 2000-2008 Michael Bayne. All Rights Reserved.