net.sf.click
Class ClickServlet

java.lang.Object
  extended byjavax.servlet.GenericServlet
      extended byjavax.servlet.http.HttpServlet
          extended bynet.sf.click.ClickServlet
All Implemented Interfaces:
Serializable, Servlet, ServletConfig

public class ClickServlet
extends HttpServlet

Provides the Click application HttpServlet.

Generally developers will simply configure the ClickServlet and will not use it directly in their code. For a Click web application to function the ClickServlet must be configured in the web application's /WEB-INF/web.xml file. A simple web application which maps all *.htm requests to a ClickServlet is provided below.

 <web-app>
    <servlet>
       <servlet-name>click-servlet</servlet-name>
       <servlet-class>net.sf.click.ClickServlet</servlet-class>
       <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
       <servlet-name>click-servlet</servlet-name>
       <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
 </web-app> 
By default the ClickServlet will attempt to load an application configuration file using the path:   /WEB-INF/click.xml

Servlet Mapping

By convention all Click page templates should have a .htm extension, and the ClickServlet should be mapped to process all *.htm URL requests. With this convention you have all the static HTML pages use a .html extension and they will not be processed as Click pages.

Load On Startup

Note you should always set load-on-startup element to be 0 so the servlet is initialized when the server is started. This will prevent any delay for the first client which uses the application.

The ClickServlet performs as much work as possible at startup to improve performance later on. The Click start up and caching strategy is configured with the Click application mode in the "click.xml" file. See the User Guide for information on how to configure the application mode.

ConfigService

A single application ConfigService instance is created by the ClickServlet at startup. Once the ConfigService has been initialized it is stored in the ServletContext using the key "net.sf.click.service.ConfigService".

Author:
Malcolm Edgar
See Also:
Serialized Form

Field Summary
protected static String CLICK_FORWARD
          The forwarded request marker attribute:   "click-forward".
protected static String CONFIG_SERVICE_CLASS
          The click application configuration service classname init parameter name:   "config-service-class".
protected  ConfigService configService
          The click application configuration service.
protected static String FORWARD_PAGE
          The Page to forward to request attribute:   "click-page".
protected  LogService logger
          The application log service.
protected  ognl.TypeConverter typeConverter
          The request parameters OGNL type converter.
 
Constructor Summary
ClickServlet()
           
 
Method Summary
protected  void activatePageInstance(Page page)
          Provides an extension point for ClickServlet sub classes to activate stateful page which may have been deserialized.
protected  Context createContext(HttpServletRequest request, HttpServletResponse response, boolean isPost)
          Creates and returns a new Context instance for this path, class and request.
protected  ControlRegistry createControlRegistry()
          Creates and returns a new ControlRegistry instance.
protected  ErrorPage createErrorPage(Class pageClass, Throwable exception)
          Creates and returns a new ErrorPage instance.
protected  Page createPage(Class pageClass, HttpServletRequest request)
          Return a new Page instance for the page Class.
protected  Page createPage(HttpServletRequest request)
          Return a new Page instance for the given request.
protected  Page createPage(String path, HttpServletRequest request)
          Return a new Page instance for the given path.
protected  PageImports createPageImports(Page page)
          Creates and returns a new PageImports instance for the specified page.
protected  Map createTemplateModel(Page page)
          Return a new VelocityContext for the given pages model and Context.
 void destroy()
           
protected  void doGet(HttpServletRequest request, HttpServletResponse response)
          Handle HTTP GET requests.
protected  void doPost(HttpServletRequest request, HttpServletResponse response)
          Handle HTTP POST requests.
protected  ConfigService getConfigService()
          Return the application configuration service instance.
protected  ognl.TypeConverter getTypeConverter()
          Return the request parameters OGNL TypeConverter.
protected  void handleException(HttpServletRequest request, HttpServletResponse response, boolean isPost, Throwable exception, Class pageClass)
          Provides the application exception handler.
protected  void handleRequest(HttpServletRequest request, HttpServletResponse response, boolean isPost)
          Handle the given servlet request and render the results to the servlet response.
 void init()
          Initialize the Click servlet and the Velocity runtime.
protected  Page initPage(String path, Class pageClass, HttpServletRequest request)
          Initialize a new page instance using newPageInstance(String, Class, HttpServletRequest) method and setting format, headers and the forward if a JSP.
protected  Page newPageInstance(String path, Class pageClass, HttpServletRequest request)
          Return a new Page instance for the given page path, class and request.
protected  void processPage(Page page)
          Process the given page invoking its "on" event callback methods and directing the response.
protected  void processPageOnDestroy(Page page, long startTime)
          Process the given pages controls onDestroy methods, reset the pages navigation state and process the pages onDestroy method.
protected  void processPageRequestParams(Page page)
          Process the page binding any request parameters to any public Page fields with the same name which are "primitive" types.
protected  void renderJSP(Page page)
          Render the given page as a JSP to the response.
protected  void renderTemplate(Page page)
          Render the Velocity template defined by the page's path.
protected  void setPageResponseHeaders(HttpServletResponse response, Map headers)
          Set the HTTP headers in the servlet response.
protected  void setRequestAttributes(Page page)
          Set the page model, context, format, messages and path as request attributes to support JSP rendering.
 
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

CONFIG_SERVICE_CLASS

protected static final String CONFIG_SERVICE_CLASS
The click application configuration service classname init parameter name:   "config-service-class".

See Also:
Constant Field Values

CLICK_FORWARD

protected static final String CLICK_FORWARD
The forwarded request marker attribute:   "click-forward".

See Also:
Constant Field Values

FORWARD_PAGE

protected static final String FORWARD_PAGE
The Page to forward to request attribute:   "click-page".

See Also:
Constant Field Values

configService

protected ConfigService configService
The click application configuration service.


logger

protected LogService logger
The application log service.


typeConverter

protected ognl.TypeConverter typeConverter
The request parameters OGNL type converter.

Constructor Detail

ClickServlet

public ClickServlet()
Method Detail

init

public void init()
          throws ServletException
Initialize the Click servlet and the Velocity runtime.

Throws:
ServletException - if the application configuration service could not be initialized
See Also:
GenericServlet.init()

destroy

public void destroy()
See Also:
GenericServlet.destroy()

doGet

protected void doGet(HttpServletRequest request,
                     HttpServletResponse response)
              throws ServletException,
                     IOException
Handle HTTP GET requests. This method will delegate the request to handleRequest(HttpServletRequest, HttpServletResponse, boolean).

Parameters:
request - the servlet request
response - the servlet response
Throws:
ServletException - if click app has not been initialized
IOException - if an I/O error occurs
See Also:
HttpServlet.doGet(HttpServletRequest, HttpServletResponse)

doPost

protected void doPost(HttpServletRequest request,
                      HttpServletResponse response)
               throws ServletException,
                      IOException
Handle HTTP POST requests. This method will delegate the request to handleRequest(HttpServletRequest, HttpServletResponse, boolean).

Parameters:
request - the servlet request
response - the servlet response
Throws:
ServletException - if click app has not been initialized
IOException - if an I/O error occurs
See Also:
HttpServlet.doPost(HttpServletRequest, HttpServletResponse)

handleRequest

protected void handleRequest(HttpServletRequest request,
                             HttpServletResponse response,
                             boolean isPost)
Handle the given servlet request and render the results to the servlet response.

If an exception occurs within this method the exception will be delegated to:

handleException(HttpServletRequest, HttpServletResponse, boolean, Throwable, Class)

Parameters:
request - the servlet request to process
response - the servlet response to render the results to
isPost - determines whether the request is a POST

handleException

protected void handleException(HttpServletRequest request,
                               HttpServletResponse response,
                               boolean isPost,
                               Throwable exception,
                               Class pageClass)
Provides the application exception handler. The application exception will be delegated to the configured error page. The default error page is ErrorPage and the page template is "click/error.htm"

Applications which wish to provide their own customized error handling must subclass ErrorPage and specify their page in the "/WEB-INF/click.xml" application configuration file. For example:

  <page path="click/error.htm" classname="com.mycorp.util.ErrorPage"/>
 
If the ErrorPage throws an exception, it will be logged as an error and then be rethrown nested inside a RuntimeException.

Parameters:
request - the servlet request with the associated error
response - the servlet response
isPost - boolean flag denoting the request method is "POST"
exception - the error causing exception
pageClass - the page class with the error

processPage

protected void processPage(Page page)
                    throws Exception
Process the given page invoking its "on" event callback methods and directing the response. This method does not invoke the "onDestroy()" callback method.

Parameters:
page - the Page to process
Throws:
Exception - if an error occurs

renderTemplate

protected void renderTemplate(Page page)
                       throws Exception
Render the Velocity template defined by the page's path.

This method creates a Velocity Context using the Page's model Map and then merges the template with the Context writing the result to the HTTP servlet response.

This method was adapted from org.apache.velocity.servlet.VelocityServlet.

Parameters:
page - the page template to merge
Throws:
Exception - if an error occurs

renderJSP

protected void renderJSP(Page page)
                  throws Exception
Render the given page as a JSP to the response.

Parameters:
page - the page to render
Throws:
Exception - if an error occurs rendering the JSP

createPage

protected Page createPage(HttpServletRequest request)
Return a new Page instance for the given request. This method will invoke initPage(String, Class, HttpServletRequest) to create the Page instance and then set the properties on the page.

Parameters:
request - the servlet request
Returns:
a new Page instance for the given request

processPageOnDestroy

protected void processPageOnDestroy(Page page,
                                    long startTime)
Process the given pages controls onDestroy methods, reset the pages navigation state and process the pages onDestroy method.

Parameters:
page - the page to process
startTime - the start time to log if greater than 0 and not in production mode

initPage

protected Page initPage(String path,
                        Class pageClass,
                        HttpServletRequest request)
Initialize a new page instance using newPageInstance(String, Class, HttpServletRequest) method and setting format, headers and the forward if a JSP.

This method will also automatically register any public Page controls in the page's model. When the page is created any public visible page Control variables will be automatically added to the page using the method Page.addControl(Control) method. If the controls name is not defined it is set to the member variables name before it is added to the page.

This feature saves you from having to manually add the controls yourself. If you don't want the controls automatically added, simply declare them as non public variables.

An example auto control registration is provided below. In this example the Table control is automatically added to the model using the name "table", and the ActionLink controls are added using the names "editDetailsLink" and "viewDetailsLink".

 public class OrderDetailsPage extends Page {

     public Table table = new Table();
     public ActionLink editDetailsLink = new ActionLink();
     publicActionLink viewDetailsLink = new ActionLink();

     public OrderDetailsPage() {
         ..
     }
 } 

Parameters:
path - the page path
pageClass - the page class
request - the page request
Returns:
initialized page

processPageRequestParams

protected void processPageRequestParams(Page page)
                                 throws ognl.OgnlException
Process the page binding any request parameters to any public Page fields with the same name which are "primitive" types. These types include string, numbers and booleans.

Type conversion is performed using the TypeConverter returned by the getTypeConverter() method.

Parameters:
page - the page whose fields are to be processed
Throws:
ognl.OgnlException - if an error occurs

newPageInstance

protected Page newPageInstance(String path,
                               Class pageClass,
                               HttpServletRequest request)
                        throws Exception
Return a new Page instance for the given page path, class and request.

The default implementation of this method simply creates new page instances:

 protected Page newPageInstance(String path, Class pageClass,
     HttpServletRequest request) throws Exception {

     return (Page) pageClass.newInstance();
 } 
This method is designed to be overridden by applications providing their own page creation patterns.

A typical example of this would be with Inversion of Control (IoC) frameworks such as Spring or HiveMind. For example a Spring application could override this method and use a ApplicationContext to instantiate new Page objects:

 protected Page newPageInstance(String path, Class pageClass,
     HttpServletRequest request) throws Exception {

     String beanName = path.substring(0, path.indexOf("."));

     if (applicationContext.containsBean(beanName)) {
         Page page = (Page) applicationContext.getBean(beanName);

     } else {
         page = (Page) pageClass.newIntance();
     }

     return page;
 } 

Parameters:
path - the request page path
pageClass - the page Class the request is mapped to
request - the page request
Returns:
a new Page object
Throws:
Exception - if an error occurs creating the Page

activatePageInstance

protected void activatePageInstance(Page page)
Provides an extension point for ClickServlet sub classes to activate stateful page which may have been deserialized.

This method does nothing and is designed for extension.

Parameters:
page - the page instance to activate

createTemplateModel

protected Map createTemplateModel(Page page)
Return a new VelocityContext for the given pages model and Context.

The following values automatically added to the VelocityContext:

Parameters:
page - the page to create a VelocityContext for
Returns:
a new VelocityContext

setPageResponseHeaders

protected void setPageResponseHeaders(HttpServletResponse response,
                                      Map headers)
Set the HTTP headers in the servlet response. The Page response headers are defined in Page.getHeaders().

Parameters:
response - the response to set the headers in
headers - the map of HTTP headers to set in the response

setRequestAttributes

protected void setRequestAttributes(Page page)
Set the page model, context, format, messages and path as request attributes to support JSP rendering. These request attributes include:

Parameters:
page - the page to set the request attributes on

getTypeConverter

protected ognl.TypeConverter getTypeConverter()
Return the request parameters OGNL TypeConverter. By default this method returns a RequestTypeConverter instance.

Returns:
the request parameters OGNL TypeConverter

createContext

protected Context createContext(HttpServletRequest request,
                                HttpServletResponse response,
                                boolean isPost)
Creates and returns a new Context instance for this path, class and request.

The default implementation of this method simply creates a new Context instance.

Subclasses can override this method to provide a custom Context.

Parameters:
request - the page request
response - the page response
isPost - true if this is a post request, false otherwise
Returns:
a Context instance

createControlRegistry

protected ControlRegistry createControlRegistry()
Creates and returns a new ControlRegistry instance.

Returns:
the new ControlRegistry instance

createErrorPage

protected ErrorPage createErrorPage(Class pageClass,
                                    Throwable exception)
Creates and returns a new ErrorPage instance.

This method creates the custom page as specified in click.xml, otherwise the default ErrorPage instance.

Subclasses can override this method to provide custom ErrorPages tailored for specific exceptions.

Note you can safely use Context in this method.

Parameters:
pageClass - the page class with the error
exception - the error causing exception
Returns:
a new ErrorPage instance

getConfigService

protected ConfigService getConfigService()
Return the application configuration service instance.

Returns:
the application configuration service instance

createPage

protected Page createPage(String path,
                          HttpServletRequest request)
Return a new Page instance for the given path.

Parameters:
path - the Page path configured in the click.xml file
request - the Page request
Returns:
a new Page object
Throws:
IllegalArgumentException - if the Page is not found

createPage

protected Page createPage(Class pageClass,
                          HttpServletRequest request)
Return a new Page instance for the page Class.

Parameters:
pageClass - the class of the Page to create
request - the Page request
Returns:
a new Page object
Throws:
IllegalArgumentException - if the Page Class is not configured with a unique path

createPageImports

protected PageImports createPageImports(Page page)
Creates and returns a new PageImports instance for the specified page.

Parameters:
page - the page to create a new PageImports instance for
Returns:
the new PageImports instance