org.apache.click
Class Context

java.lang.Object
  extended by org.apache.click.Context

public class Context
extends Object

Provides the HTTP request context information for pages and controls. A new Context object is created for each Page request. The request Context object can be obtained from the thread local variable via the getThreadLocalContext() method.


Field Summary
protected  ServletConfig config
          The servlet config.
protected  ServletContext context
          The servlet context.
protected  boolean isPost
          The HTTP method is POST flag.
static String LOCALE
          The user's session Locale key:   locale.
protected  HttpServletResponse response
          The servlet response.
 
Constructor Summary
Context(ServletContext context, ServletConfig config, HttpServletRequest request, HttpServletResponse response, boolean isPost, ClickServlet clickServlet)
          Create a new request context.
 
Method Summary
 Map<String,String> createMessagesMap(Class<?> baseClass, String globalResource)
          Return a new messages map for the given baseClass (a page or control) and the given global resource bundle name.
<T extends Page>
T
createPage(Class<T> pageClass)
          Return a new Page instance for the given class.
<T extends Page>
T
createPage(String path)
          Return a new Page instance for the given path.
 String getApplicationMode()
          Return the Click application mode value:   ["production", "profile", "development", "debug", "trace"].
 String getCharset()
          Return the Click application charset or ISO-8859-1 if not is defined.
 Cookie getCookie(String name)
          Return the cookie for the given name or null if not found.
 String getCookieValue(String name)
          Return the cookie value for the given name or null if not found.
 FileItem getFileItem(String name)
          Returns the value of a request parameter as a FileItem, for "multipart" POST requests (file uploads), or null if the parameter is not found.
 Map<String,FileItem[]> getFileItemMap()
          Returns a map of FileItem arrays keyed on request parameter name for "multipart" POST requests (file uploads).
 Locale getLocale()
          Return the users Locale.
 Class<? extends Page> getPageClass(String path)
          Return the page Class for the given path.
 String getPagePath(Class<? extends Page> pageClass)
          Return the path for the given page Class.
 HttpServletRequest getRequest()
          Returns the servlet request.
 Object getRequestAttribute(String name)
          Return the named request attribute, or null if not defined.
 String getRequestParameter(String name)
          Return the named request parameter.
 String[] getRequestParameterValues(String name)
          Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.
 String getResourcePath()
          Return the page resource path from the request.
 HttpServletResponse getResponse()
          Returns the servlet response.
 ServletConfig getServletConfig()
          Returns the servlet config.
 ServletContext getServletContext()
          Returns the servlet context.
 HttpSession getSession()
          Return the user's HttpSession, creating one if necessary.
 Object getSessionAttribute(String name)
          Return the named session attribute, or null if not defined.
static Context getThreadLocalContext()
          Return the thread local request context instance.
 boolean hasRequestAttribute(String name)
          Return true if the request contains the named attribute.
 boolean hasRequestParameter(String name)
          Return true if the request contains the named parameter.
 boolean hasSession()
          Return true if a HttpSession exists, or false otherwise.
 boolean hasSessionAttribute(String name)
          Return true if there is a session and it contains the named attribute.
static boolean hasThreadLocalContext()
          Returns true if a Context instance is available on the current thread, false otherwise.
 void invalidateCookie(String name)
          Invalidate the specified cookie and delete it from the response object.
 boolean isAjaxRequest()
          Return true is this is an Ajax request, false otherwise.
 boolean isForward()
          Return true if the request has been forwarded.
 boolean isGet()
          Return true if the HTTP request method is "GET".
 boolean isMultipartRequest()
          Return true if the request is a multi-part content type POST request.
 boolean isPost()
          Return true if the HTTP request method is "POST".
 void removeSessionAttribute(String name)
          Remove the named attribute from the session.
 String renderTemplate(Class templateClass, Map<String,?> model)
          Return a rendered Velocity template and model for the given class and model data.
 String renderTemplate(String templatePath, Map<String,?> model)
          Return a rendered Velocity template and model data.
 Cookie setCookie(String name, String value, int maxAge)
          Sets the given cookie value in the servlet response with the path "/".
 void setFlashAttribute(String name, Object value)
          This method will set the named object as a flash HttpSession object.
 void setLocale(Locale locale)
          This method stores the given Locale in the users session.
 void setRequestAttribute(String name, Object value)
          This method will set the named object in the HTTP request.
 void setSessionAttribute(String name, Object value)
          This method will set the named object in the HttpSession.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

LOCALE

public static final String LOCALE
The user's session Locale key:   locale.

See Also:
Constant Field Values

context

protected final ServletContext context
The servlet context.


config

protected final ServletConfig config
The servlet config.


isPost

protected final boolean isPost
The HTTP method is POST flag.


response

protected final HttpServletResponse response
The servlet response.

Constructor Detail

Context

public Context(ServletContext context,
               ServletConfig config,
               HttpServletRequest request,
               HttpServletResponse response,
               boolean isPost,
               ClickServlet clickServlet)
Create a new request context.

Parameters:
context - the servlet context
config - the servlet config
request - the servlet request
response - the servlet response
isPost - the servlet request is a POST
clickServlet - the click servlet instance
Method Detail

getThreadLocalContext

public static Context getThreadLocalContext()
Return the thread local request context instance.

Returns:
the thread local request context instance.
Throws:
RuntimeException - if a Context is not available on the thread.

hasThreadLocalContext

public static boolean hasThreadLocalContext()
Returns true if a Context instance is available on the current thread, false otherwise. Unlike getThreadLocalContext() this method can safely be used and will not throw an exception if Context is not available on the current thread.

This method is very useful inside a Control constructor which might need access to the Context. As Controls could potentially be instantiated during Click startup (in order to deploy their resources), this check can be used to determine whether Context is available or not.

For example:

 public MyControl extends AbstractControl {
     public MyControl(String name) {
         if (Context.hasThreadLocalContext()) {
             // Context is available, meaning a user initiated a web
             // request
             Context context = getContext();
             String state = (String) context.getSessionAttribute(name);
             setValue(state);
         } else {
             // No Context is available, meaning this is most probably
             // the application startup and deployment phase.
         }
     }
 }
 

Returns:
true if a Context instance is available on the current thread, false otherwise

getRequest

public HttpServletRequest getRequest()
Returns the servlet request.

Returns:
HttpServletRequest

getResponse

public HttpServletResponse getResponse()
Returns the servlet response.

Returns:
HttpServletResponse

getServletConfig

public ServletConfig getServletConfig()
Returns the servlet config.

Returns:
ServletConfig

getServletContext

public ServletContext getServletContext()
Returns the servlet context.

Returns:
ServletContext

getSession

public HttpSession getSession()
Return the user's HttpSession, creating one if necessary.

Returns:
the user's HttpSession, creating one if necessary.

getResourcePath

public String getResourcePath()
Return the page resource path from the request. For example:
 http://www.mycorp.com/banking/secure/login.htm  ->  /secure/login.htm 

Returns:
the page resource path from the request

isForward

public boolean isForward()
Return true if the request has been forwarded. A forwarded request will contain a ClickServlet.CLICK_FORWARD request attribute.

Returns:
true if the request has been forwarded

isPost

public boolean isPost()
Return true if the HTTP request method is "POST".

Returns:
true if the HTTP request method is "POST"

isGet

public boolean isGet()
Return true if the HTTP request method is "GET".

Returns:
true if the HTTP request method is "GET"

isAjaxRequest

public boolean isAjaxRequest()
Return true is this is an Ajax request, false otherwise.

An Ajax request is identified by the presence of the request header or request parameter: "X-Requested-With". "X-Requested-With" is the de-facto standard identifier used by Ajax libraries.

Note: incoming requests that contains a request parameter "X-Requested-With" will result in this method returning true, even though the request itself was not initiated through a XmlHttpRequest object. This allows one to programmatically enable Ajax requests. A common use case for this feature is when uploading files through an IFrame element. By specifying "X-Requested-With" as a request parameter the IFrame request will be handled like a normal Ajax request.

Returns:
true if this is an Ajax request, false otherwise

hasRequestAttribute

public boolean hasRequestAttribute(String name)
Return true if the request contains the named attribute.

Parameters:
name - the name of the request attribute
Returns:
true if the request contains the named attribute

getRequestAttribute

public Object getRequestAttribute(String name)
Return the named request attribute, or null if not defined.

Parameters:
name - the name of the request attribute
Returns:
the named request attribute, or null if not defined

setRequestAttribute

public void setRequestAttribute(String name,
                                Object value)
This method will set the named object in the HTTP request.

Parameters:
name - the storage name for the object in the request
value - the object to store in the request

hasRequestParameter

public boolean hasRequestParameter(String name)
Return true if the request contains the named parameter.

Parameters:
name - the name of the request parameter
Returns:
true if the request contains the named parameter

getRequestParameter

public String getRequestParameter(String name)
Return the named request parameter. This method supports "multipart/form-data" POST requests and should be used in preference to the HttpServletRequest method getParameter().

Parameters:
name - the name of the request parameter
Returns:
the value of the request parameter.
See Also:
Form.onProcess(), isMultipartRequest(), getFileItemMap()

getRequestParameterValues

public String[] getRequestParameterValues(String name)
Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.

Parameters:
name - a String containing the name of the parameter whose value is requested
Returns:
an array of String objects containing the parameter's values

getSessionAttribute

public Object getSessionAttribute(String name)
Return the named session attribute, or null if not defined.

If the session is not defined this method will return null, and a session will not be created.

This method supports FlashAttribute which when accessed are then removed from the session.

Parameters:
name - the name of the session attribute
Returns:
the named session attribute, or null if not defined

setSessionAttribute

public void setSessionAttribute(String name,
                                Object value)
This method will set the named object in the HttpSession.

This method will create a session if one does not already exist.

Parameters:
name - the storage name for the object in the session
value - the object to store in the session

removeSessionAttribute

public void removeSessionAttribute(String name)
Remove the named attribute from the session. If the session does not exist or the name is null, this method does nothing.

Parameters:
name - of the attribute to remove from the session

hasSessionAttribute

public boolean hasSessionAttribute(String name)
Return true if there is a session and it contains the named attribute.

Parameters:
name - the name of the attribute
Returns:
true if the session contains the named attribute

hasSession

public boolean hasSession()
Return true if a HttpSession exists, or false otherwise.

Returns:
true if a HttpSession exists, or false otherwise

setFlashAttribute

public void setFlashAttribute(String name,
                              Object value)
This method will set the named object as a flash HttpSession object.

The flash object will exist in the session until it is accessed once, and then removed. Flash objects are typically used to display a message once.

Parameters:
name - the storage name for the object in the session
value - the object to store in the session

getCookie

public Cookie getCookie(String name)
Return the cookie for the given name or null if not found.

Parameters:
name - the name of the cookie
Returns:
the cookie for the given name or null if not found

getCookieValue

public String getCookieValue(String name)
Return the cookie value for the given name or null if not found.

Parameters:
name - the name of the cookie
Returns:
the cookie value for the given name or null if not found

setCookie

public Cookie setCookie(String name,
                        String value,
                        int maxAge)
Sets the given cookie value in the servlet response with the path "/".

Parameters:
name - the cookie name
value - the cookie value
maxAge - the maximum age of the cookie in seconds. A negative value will expire the cookie at the end of the session, while 0 will delete the cookie.
Returns:
the Cookie object created and set in the response
See Also:
ClickUtils.setCookie(HttpServletRequest, HttpServletResponse, String, String, int, String)

invalidateCookie

public void invalidateCookie(String name)
Invalidate the specified cookie and delete it from the response object. Deletes only cookies mapped against the root "/" path.

Parameters:
name - the name of the cookie you want to delete.
See Also:
ClickUtils.invalidateCookie(HttpServletRequest, HttpServletResponse, String)

createPage

public <T extends Page> T createPage(String path)
Return a new Page instance for the given path.

This method can be used to create a target page for the Page.setForward(Page), for example:

 UserEdit userEdit = (UserEdit) getContext().createPage("/user-edit.htm");
 userEdit.setUser(user);

 setForward(userEdit); 
The given page path must start with a '/'.

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

createPage

public <T extends Page> T createPage(Class<T> pageClass)
Return a new Page instance for the given class.

This method can be used to create a target page for the Page.setForward(Page), for example:

 UserEdit userEdit = (UserEdit) getContext().createPage(UserEdit.class);
 userEdit.setUser(user);

 setForward(userEdit); 

Parameters:
pageClass - the Page class as configured in the click.xml file
Returns:
a new Page object
Throws:
IllegalArgumentException - if the Page is not found, or is not configured with a unique path

getPagePath

public String getPagePath(Class<? extends Page> pageClass)
Return the path for the given page Class.

Parameters:
pageClass - the class of the Page to lookup the path for
Returns:
the path for the given page Class
Throws:
IllegalArgumentException - if the Page Class is not configured with a unique path

getPageClass

public Class<? extends Page> getPageClass(String path)
Return the page Class for the given path.

Parameters:
path - the page path
Returns:
the page class for the given path
Throws:
IllegalArgumentException - if the Page Class for the path is not found

getApplicationMode

public String getApplicationMode()
Return the Click application mode value:   ["production", "profile", "development", "debug", "trace"].

Returns:
the application mode value

getCharset

public String getCharset()
Return the Click application charset or ISO-8859-1 if not is defined.

The charset is defined in click.xml through the charset attribute on the click-app element.

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <click-app charset="UTF-8">
    ..
 </click-app> 

Returns:
the application charset or ISO-8859-1 if not defined

createMessagesMap

public Map<String,String> createMessagesMap(Class<?> baseClass,
                                            String globalResource)
Return a new messages map for the given baseClass (a page or control) and the given global resource bundle name.

Parameters:
baseClass - the target class
globalResource - the global resource bundle name
Returns:
a new messages map with the messages for the target.

getFileItemMap

public Map<String,FileItem[]> getFileItemMap()
Returns a map of FileItem arrays keyed on request parameter name for "multipart" POST requests (file uploads). Thus each map entry will consist of one or more FileItem objects.

Returns:
map of FileItem arrays keyed on request parameter name for "multipart" POST requests

getFileItem

public FileItem getFileItem(String name)
Returns the value of a request parameter as a FileItem, for "multipart" POST requests (file uploads), or null if the parameter is not found.

If there were multivalued parameters in the request (ie two or more file upload fields with the same name), the first fileItem in the array is returned.

Parameters:
name - the name of the parameter of the fileItem to retrieve
Returns:
the fileItem for the specified name

getLocale

public Locale getLocale()
Return the users Locale.

If the users Locale is stored in their session this will be returned. Else if the click-app configuration defines a default Locale this value will be returned, otherwise the request's Locale will be returned.

To override the default request Locale set the users Locale using the setLocale(Locale) method.

Pages and Controls obtain the users Locale using this method.

Returns:
the users Locale in the session, or if null the request Locale

setLocale

public void setLocale(Locale locale)
This method stores the given Locale in the users session. If the given Locale is null, the "locale" attribute will be removed from the session.

The Locale object is stored in the session using the LOCALE key.

Parameters:
locale - the Locale to store in the users session using the key "locale"

isMultipartRequest

public boolean isMultipartRequest()
Return true if the request is a multi-part content type POST request.

Returns:
true if the request is a multi-part content type POST request

renderTemplate

public String renderTemplate(Class templateClass,
                             Map<String,?> model)
Return a rendered Velocity template and model for the given class and model data.

This method will merge the class .htm Velocity template and model data using the applications Velocity Engine.

An example of the class template resolution is provided below:

 // Full class name
 com.mycorp.control.CustomTextField

 // Template path name
 /com/mycorp/control/CustomTextField.htm 
Example method usage:
 public String toString() {
     Map model = getModel();
     return getContext().renderTemplate(getClass(), model);
 } 

Parameters:
templateClass - the class to resolve the template for
model - the model data to merge with the template
Returns:
rendered Velocity template merged with the model data
Throws:
RuntimeException - if an error occurs

renderTemplate

public String renderTemplate(String templatePath,
                             Map<String,?> model)
Return a rendered Velocity template and model data.

Example method usage:

 public String toString() {
     Map model = getModel();
     return getContext().renderTemplate("/custom-table.htm", model);
 } 

Parameters:
templatePath - the path of the Velocity template to render
model - the model data to merge with the template
Returns:
rendered Velocity template merged with the model data
Throws:
RuntimeException - if an error occurs