org.apache.click
Class ClickServlet

java.lang.Object
  extended by javax.servlet.GenericServlet
      extended by javax.servlet.http.HttpServlet
          extended by org.apache.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>org.apache.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 "org.apache.click.service.ConfigService".

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.MemberAccess memberAccess
          The OGNL member access handler.
protected  ResourceService resourceService
          The application resource service.
protected static String TYPE_CONVERTER_CLASS
          The custom TypeConverter classname as an init parameter name: &nbps; "type-converter-class".
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  ActionEventDispatcher createActionEventDispatcher()
          Creates and returns a new ActionEventDispatcher instance.
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<? extends Page> pageClass, Throwable exception)
          Creates and returns a new ErrorPage instance.
protected
<T extends Page>
T
createPage(Class<T> pageClass, HttpServletRequest request)
          Return a new Page instance for the page Class.
protected  Page createPage(Context context)
          Return a new Page instance for the given request context.
protected
<T extends Page>
T
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<String,Object> 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 handleAjaxException(HttpServletRequest request, HttpServletResponse response, boolean isPost, Throwable exception, Class<? extends Page> pageClass)
          Provides an Ajax exception handler.
protected  void handleException(HttpServletRequest request, HttpServletResponse response, boolean isPost, Throwable exception, Class<? extends Page> 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<? extends Page> 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<? extends Page> pageClass, HttpServletRequest request)
          Return a new Page instance for the given page path, class and request.
protected  void performOnInit(Page page, Context context)
          Perform the onInit event callback for the specified page.
protected  void performOnPostOrGet(Page page, Context context, boolean isPost)
          Perform onPost or onGet event callback for the specified page.
protected  boolean performOnProcess(Page page, Context context, ActionEventDispatcher eventDispatcher)
          Perform onProcess event callback for the specified page, returning true if processing should continue, false otherwise.
protected  void performOnRender(Page page, Context context)
          Perform onRender event callback for the specified page.
protected  boolean performOnSecurityCheck(Page page, Context context)
          Perform the onSecurityCheck event callback for the specified page, returning true if processing should continue, false otherwise.
protected  ActionResult performPageAction(Page page, String pageAction, Context context)
          Perform the page action for the given page and return the action result.
protected  void performRender(Page page, Context context)
          Performs rendering of the specified page.
protected  void performRender(Page page, Context context, ActionResult actionResult)
          Performs rendering of the specified page.
protected  void processAjaxPageEvents(Page page, Context context)
          Process the given page events, invoking the "on" event callback methods and directing the response.
protected  boolean processAjaxTargetControls(Context context, ActionEventDispatcher eventDispatcher, ControlRegistry controlRegistry)
          Process all Ajax target controls and return true if the page should continue processing, false otherwise.
protected  void processPage(Page page)
          Process the given page invoking its "on" event callback methods and directing the response.
protected  void processPageEvents(Page page, Context context)
          Process the given page events, invoking the "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 renderActionResult(ActionResult actionResult, Page page, Context context)
          Render the given ActionResult.
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<String,Object> 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

TYPE_CONVERTER_CLASS

protected static final String TYPE_CONVERTER_CLASS
The custom TypeConverter classname as an init parameter name: &nbps; "type-converter-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.


memberAccess

protected ognl.MemberAccess memberAccess
The OGNL member access handler.


resourceService

protected ResourceService resourceService
The application resource 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.

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

destroy

public void destroy()
Specified by:
destroy in interface Servlet
Overrides:
destroy in class GenericServlet
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).

Overrides:
doGet in class HttpServlet
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).

Overrides:
doPost in class HttpServlet
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)
                      throws IOException
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
Throws:
IOException - if resource request could not be served

handleException

protected void handleException(HttpServletRequest request,
                               HttpServletResponse response,
                               boolean isPost,
                               Throwable exception,
                               Class<? extends Page> 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
See Also:
processPageEvents(org.apache.click.Page, org.apache.click.Context)

processPageEvents

protected void processPageEvents(Page page,
                                 Context context)
                          throws Exception
Process the given page events, invoking the "on" event callback methods and directing the response.

This method does not invoke the "onDestroy()" callback method.

Parameters:
page - the Page which events to process
context - the request context
Throws:
Exception - if an error occurs

performOnSecurityCheck

protected boolean performOnSecurityCheck(Page page,
                                         Context context)
Perform the onSecurityCheck event callback for the specified page, returning true if processing should continue, false otherwise.

Parameters:
page - the page to perform the security check on
context - the request context
Returns:
true if processing should continue, false otherwise

performPageAction

protected ActionResult performPageAction(Page page,
                                         String pageAction,
                                         Context context)
Perform the page action for the given page and return the action result.

Parameters:
page - the page which action to perform
pageAction - the name of the page action
context - the request context
Returns:
the page action ActionResult instance

performOnInit

protected void performOnInit(Page page,
                             Context context)
Perform the onInit event callback for the specified page.

Parameters:
page - the page to initialize
context - the request context

performOnProcess

protected boolean performOnProcess(Page page,
                                   Context context,
                                   ActionEventDispatcher eventDispatcher)
Perform onProcess event callback for the specified page, returning true if processing should continue, false otherwise.

Parameters:
page - the page to process
context - the request context
eventDispatcher - the action event dispatcher
Returns:
true if processing should continue, false otherwise

performOnPostOrGet

protected void performOnPostOrGet(Page page,
                                  Context context,
                                  boolean isPost)
Perform onPost or onGet event callback for the specified page.

Parameters:
page - the page for which the onGet or onPost is performed
context - the request context
isPost - specifies whether the request is a post or a get

performOnRender

protected void performOnRender(Page page,
                               Context context)
Perform onRender event callback for the specified page.

Parameters:
page - page to render
context - the request context

performRender

protected void performRender(Page page,
                             Context context)
                      throws Exception
Performs rendering of the specified page.

Parameters:
page - page to render
context - the request context
Throws:
Exception - if error occurs

performRender

protected void performRender(Page page,
                             Context context,
                             ActionResult actionResult)
                      throws Exception
Performs rendering of the specified page.

Parameters:
page - page to render
context - the request context
actionResult - the action result
Throws:
Exception - if 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

renderActionResult

protected void renderActionResult(ActionResult actionResult,
                                  Page page,
                                  Context context)
Render the given ActionResult. If the action result is null, nothing is rendered.

Parameters:
actionResult - the action result to render
page - the requested page
context - the request context

createPage

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

Parameters:
context - the page request context
Returns:
a new Page instance for the given request, or null if an PageInterceptor has aborted page creation

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<? extends Page> 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<? extends Page> 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.newInstance();
     }

     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<String,Object> 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
See Also:
ClickUtils.createTemplateModel(org.apache.click.Page, org.apache.click.Context)

setPageResponseHeaders

protected void setPageResponseHeaders(HttpServletResponse response,
                                      Map<String,Object> 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()
                                       throws RuntimeException
Return the request parameters OGNL TypeConverter. This method performs a lazy load of the TypeConverter object, using the classname defined in the Servlet init parameter type-converter-class, if this parameter is not defined this method will return a RequestTypeConverter instance.

Returns:
the request parameters OGNL TypeConverter
Throws:
RuntimeException - if the TypeConverter instance could not be created

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

createActionEventDispatcher

protected ActionEventDispatcher createActionEventDispatcher()
Creates and returns a new ActionEventDispatcher instance.

Returns:
the new ActionEventDispatcher instance

createControlRegistry

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

Returns:
the new ControlRegistry instance

createErrorPage

protected ErrorPage createErrorPage(Class<? extends Page> 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 <T extends Page> T createPage(String path,
                                        HttpServletRequest request)
Return a new Page instance for the given path. The path must start with a "/".

Parameters:
path - the path which maps to a Page class
request - the Page request
Returns:
a new Page object
Throws:
IllegalArgumentException - if the Page is not found

createPage

protected <T extends Page> T createPage(Class<T> 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

processAjaxPageEvents

protected void processAjaxPageEvents(Page page,
                                     Context context)
                              throws Exception
Process the given page events, invoking the "on" event callback methods and directing the response.

Parameters:
page - the page which events to process
context - the request context
Throws:
Exception - if an error occurs

processAjaxTargetControls

protected boolean processAjaxTargetControls(Context context,
                                            ActionEventDispatcher eventDispatcher,
                                            ControlRegistry controlRegistry)
Process all Ajax target controls and return true if the page should continue processing, false otherwise.

Parameters:
context - the request context
eventDispatcher - the event dispatcher
controlRegistry - the control registry
Returns:
true if the page should continue processing, false otherwise

handleAjaxException

protected void handleAjaxException(HttpServletRequest request,
                                   HttpServletResponse response,
                                   boolean isPost,
                                   Throwable exception,
                                   Class<? extends Page> pageClass)
Provides an Ajax exception handler. Exceptions are wrapped inside a div element and streamed back to the browser. The response status is set to an HTTP 500 error which allows the JavaScript that initiated the Ajax request to handle the error as appropriate.

If Click is running in development modes the exception stackTrace will be rendered, in production modes an error message is rendered.

Below is an example error response:

 <div id='errorReport' class='errorReport'>
 The application encountered an unexpected error.
 </div>
 

Parameters:
request - the servlet request
response - the servlet response
isPost - determines whether the request is a POST
exception - the error causing exception
pageClass - the page class with the error