TagLib documentation

org.alweb.doff.core
Class Service

java.lang.Object
  extended by org.alweb.doff.util.error.ErrorContainer
      extended by org.alweb.doff.core.Service
All Implemented Interfaces:
ErrorProducer
Direct Known Subclasses:
Controller, Filter

public abstract class Service
extends ErrorContainer

Represents an interface to control and manage HTTP requests and responses easier.

An new instance of a Service is constructed for each HTTP request.

You should better override init() method instead of defining a constructor for your services. But, if you really want to declare your own constructors, you must at least provide a default constructor. This constructor can be private, protected or public.

Author:
Alexis Toulotte

Field Summary
static String FRAGMENTS_EXTENSION
          The default fragments extension (.jspf).
static String VIEWS_EXTENSION
          The default views extension (.jsp).
static String VIEWS_PATH
          The default views path (/WEB-INF/views).
 
Constructor Summary
Service()
           
 
Method Summary
 void addCookie(String name, String value)
          Creates a session cookie (means that cookie will expire when the browser is closed).
 void addCookie(String name, String value, int maxAge)
          Tries to create a cookie on the client browser.
 void addHeader(Header header, Object value)
          Adds a response header with the given header and value.
 void addHeader(String name, Object value)
          Adds a response header with the given name and value.
 void disableBrowserCache()
          Tries to disables browser cache on current response.
 String encodeRedirectURL(String url)
           Invokes this method in order to obtain the redirect URL.
 String encodeRedirectURL(String url, boolean includeServletPath)
          Invokes this method in order to obtain the redirect URL.
 String encodeURL(String url)
           Invokes this method in order to obtain the encoded URL.
 String encodeURL(String url, boolean includeServletPath)
          Invokes this method in order to obtain the encoded URL.
 void flash(String name, Object value)
           This method sets an attribute into the session and then, into request in order to be displayed after a redirect.
 void forwardRequest(String path)
          Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
 ActionMapping getAction()
           Returns the action mapped by current URL or null if there is no action (or no controller) matching current URL.
 URL getCompleteURL(boolean includeQueryString)
          Returns the complete URL include host, port.
 URL getCompleteURL(Class<? extends Controller> controllerClass, String methodName, Object... extraInfos)
          Returns the complete (with scheme and host) URL of the specified action.
 String getContextPath()
          Returns the portion of the request URI that indicates the context of the request.
 Parameter getCookie(String name)
          A convenience helper to extract a cookie value as a Parameter.
 Map<String,Parameter> getCookies()
          Returns a Map containing all of the Cookie objects the client sent with this request.
 Collection<ErrorMessage> getErrors()
          Returns all errors into the current request.
protected  FileUploadBase getFileUpload()
           Returns a unique FileUploadBase instance for handling file upload.
 Parameter getHeader(Header header)
           Returns the value of the specified request header.
 Parameter getHeader(String name)
           Returns the value of the specified request header.
 Map<String,Parameter> getHeaders()
          Returns a map of all the header names and value this request contains.
 String getHost()
          Returns the host specified into the current request.
 Locale getLocale()
           Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.
 Method getMethod()
          Returns the current HTTP method.
 ServletOutputStream getOutputStream()
          Returns a ServletOutputStream suitable for writing binary data in the response.
 Parameter getParam(String name)
           Returns the value of a request parameter.
<T> T
getParamOrSessionAttr(String paramName, String sessionAttr, T defaultValue)
          Returns the parameter of specified name with specified default value or load it from session if not exists.
<T> T
getParamOrSessionAttr(String name, T defaultValue)
          Returns the parameters of specified name with specified default value or load it from session if not exists.
 Map<String,Parameter> getParams()
           Returns a Map of parameters of a request.
 Collection<Parameter> getParams(String name)
           Returns a Collection of parameters of a request.
 String getPathInfo()
          Returns any extra path information associated with current URL.
 String getPathInfoWithQueryString()
          Returns the path info with the query string after if present.
 Parameter getPathParam()
          Returns the first variable part of the current path.
 Parameter getPathParam(int index)
          Returns the variable part of the current path.
 int getPort()
          Returns the port of the request, it can be 8080, 80, etc.
 Protocol getProtocol()
          Returns the current protocol of the request.
 String getPublicURL(String path)
          Returns the public URL of specified path.
 String getQueryString()
          Returns the query string or the empty string if missing.
 String getRemoteAddress()
          Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.
 HttpServletRequest getRequest()
          Returns the current request.
 Object getRequestAttribute(String name)
          Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.
 HttpServletResponse getResponse()
          Returns the current response.
 Locale getResponseLocale()
           Returns the locale specified for this response using the setLocale(Locale) method.
protected  ServiceMapping getServiceMapping()
          Returns the mapping of this service instance.
protected  HttpServlet getServlet()
          Returns the servlet associated to this Service object.
 HttpSession getSession()
          Returns the current session associated with this request, or if the request does not have a session, creates one.
<T> T
getSessionAttribute(String name, T defaultValue)
          Returns the session attribute of specified name.
static String getSessionAttributeName(Class<? extends Service> serviceClass, String identifier)
          Provides a way to create a HttpSession attribute name.
 FileItem getUploadedFile()
           A convenience helper to extract the unique uploaded file by the client browser.
 FileItem getUploadedFile(String name)
           Returns a FileItem uploaded from the client browser or null if there is no file represented by the specified name.
 Map<String,FileItem> getUploadedFiles()
           Returns a map of uploaded files by the client browser.
 String getURL()
          A convenience helper to retrieve the current relative URL with the servlet path but without path info and query string.
 String getURL(boolean includeQueryString)
          A convenience helper to retrieve the current relative URL.
 String getURL(boolean relative, boolean includeServletPath, boolean includePathInfo, boolean includeQueryString)
          Retrieves the current URL.
 String getURL(Class<? extends Controller> controllerClass, String methodName, Object... extraInfos)
          Returns the URL of the specified action.
 PrintWriter getWriter()
          Returns a PrintWriter object that can send character text to the client.
 boolean hasParam(String name)
          Determines whether a parameter exists.
protected  void init()
           Method used to be overridden.
 boolean isAjaxRequest()
          Determines if request is an Ajax request.
 boolean isHttpsRequest()
          Determines if current request is an HTTPS request.
 boolean isLocalRequest()
          Determines if the the remove address is a local address.
 Pagination paginate(Collection items)
          Creates a new pagination object and set it into current request.
 Pagination paginate(Collection items, Integer maxItemCountPerPage)
          Creates a new pagination object and set it into current request.Items count is determined from Collection.size() method.
 Pagination paginate(Integer itemCount)
          Creates a new pagination object and set it into current request.
 Pagination paginate(Integer itemCount, Integer maxItemCountPerPage)
          Creates a new pagination object and set it into current request.
 void print(Object... objects)
          Prints specified objects on servlet output stream.
 void println(Object... objects)
          Prints specified objects on servlet output stream and a end of line delimiter after each object.
 void redirect(Class<? extends Controller> controllerClass, String methodName, Object... extraInfos)
          Redirect to the specified action.
 void redirect(String url)
           Invoke this when your doPost method is done with business logic, and therefore needs to redirect the user's browser to a result page accessed through a regular HTTP GET.
 void redirect(String url, boolean includeServletPath)
          Invoke this when your doPost method is done with business logic, and therefore needs to redirect the user's browser to a result page accessed through a regular HTTP GET.
 void redirect(URL url)
          Invoke this in order to redirect the user's browser to the specified URL.
 void redirectToPublic(String path)
          Makes a redirection to a public document.
 void removeCookie(String name)
          Tries to remove the cookie identified by the specified name.
 void removeCookies(boolean keepSessionCookie)
          Tries to remove all cookies currently stored on the user's browser.
 void removeSessionAttributes(String... exclusions)
          Removes all attributes into the current user session.
 void renderFile(File file)
          Renders specified file to the output stream.
 void renderFile(File file, String contentType)
          Renders specified file to the output stream.
 void renderFile(String file)
          Renders specified file to the output stream.
 void renderFile(String file, String contentType)
          Renders specified file to the output stream.
 void renderFragment()
           Invoke this to forward control to the view's JSP.
 void renderFragment(Class<? extends Controller> controllerClass, String methodName)
           Invoke this to forward control to the view's JSP.
 void renderFragment(String name)
           Invoke this to forward control to the view's JSP.
 void renderFragment(String name, String directory, String extension)
          Invoke this to forward control to the view's JSP.
 void renderStream(InputStream in)
          Renders specified stream to the output buffer.
 void renderStream(InputStream in, int bufferSize)
          Renders specified stream to the output buffer.
 void renderView()
           Invoke this to forward control to the view's JSP.
 void renderView(Class<? extends Controller> controllerClass, String methodName)
           Invoke this to forward control to the view's JSP.
 void renderView(String name)
          Invoke this to forward control to the view's JSP.
 void renderView(String name, String directory, String extension)
          Invoke this to forward control to the view's JSP.
 boolean responseContainsHeader(Header header)
          Determines if the current response contains specified header.
 boolean responseContainsHeader(String header)
          Determines if the current response contains specified header.
 void sendError(Code code, String message)
          Sends an error response to the client using the specified status.
 void sendError(int code, String message)
           Sends an error response to the client using the specified status.
 void sendError(String message)
          A convenience helper to send a 500 error (Code.INTERNAL_SERVER_ERROR) to the client browser.
 void sendNotFound()
          Sends a 404 (Code.NOT_FOUND) error to the client's browser.
 void sendPermissionDenied()
          Sends "Permission Denied" (403 HTTP code) to the client browser.
 void setContentType(String type)
          Sets the content type of the response being sent to the client, if the response has not been committed yet.
 void setExpires(Date date)
          Sets the expires header to specified date.
 void setHeader(Header header, Object value)
          Sets a response header with the given enumeration and value.
 void setHeader(String name, Object value)
          Sets a response header with the given name and value.
 void setLastModified(Date date)
          Sets the last modified header to specified date.
 void setLocale(Locale locale)
          Sets the locale of the response, if the response has not been committed yet.
 void setOutputFilename(String filename)
          Sets the filename of the output.
 void setOutputFilename(String filename, String contentType)
          Sets the filename of the output.
 void setRequestAttribute(String name, Object value)
          A convenience helper to set an attribute into the current request.
 String toString()
          Provides a string representation of this Service object.
 
Methods inherited from class org.alweb.doff.util.error.ErrorContainer
addError, addError, addErrors, addErrors, addErrors, clearErrors, isInErrorState
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

FRAGMENTS_EXTENSION

public static final String FRAGMENTS_EXTENSION
The default fragments extension (.jspf).

See Also:
Constant Field Values

VIEWS_EXTENSION

public static final String VIEWS_EXTENSION
The default views extension (.jsp).

Since:
1.1
See Also:
renderView(), Constant Field Values

VIEWS_PATH

public static final String VIEWS_PATH
The default views path (/WEB-INF/views).

Since:
1.1
See Also:
renderView(), Constant Field Values
Constructor Detail

Service

public Service()
Method Detail

getSessionAttributeName

public static String getSessionAttributeName(Class<? extends Service> serviceClass,
                                             String identifier)
Provides a way to create a HttpSession attribute name. This methods prints a debug message each time when it is invoked. The little debug message is useful when you think that some attribute names are in conflict. This method should be called when initializing class constants.

Parameters:
serviceClass - The class where attribute's name is declared as constant.
identifier - An identifier for the attribute.
Returns:
The name of the service, a dot and the specified identified.
Throws:
NullPointerException - if specified service class is null.
IllegalArgumentException - if specified identifier (trimmed) is null or the empty string.
See Also:
ServiceMapping.getName()

getFileUpload

protected FileUploadBase getFileUpload()

Returns a unique FileUploadBase instance for handling file upload. This method can be overridden for customizing file uploads.

The default size limit of a file upload request is 2 megabytes (2097152 bytes). If you want to change this limit, override this method and customize the returned value or call getFileUpload().setSizeMax(yourLimit) method. Don't forget to invoke setSizeMax method before trying to obtain parameters or uploaded files, otherwise your limit will be ignored.

Since:
1.0
See Also:
getUploadedFile(String), FileUploadBase.setSizeMax(long), ServletFileUpload, DiskFileItemFactory

getServiceMapping

protected final ServiceMapping getServiceMapping()
Returns the mapping of this service instance.

Since:
1.5.1

getServlet

protected final HttpServlet getServlet()
Returns the servlet associated to this Service object.

See Also:
ServletParameters.getServlet()

init

protected void init()

Method used to be overridden. This method is invoked for each new request on this Service. It's not useful to call super.init() when override.

You should better override this method instead of defining a constructor for your services. But, if you really want to declare your own constructors, you must at least provide a default constructor. This constructor can be private, protected or public.


addCookie

public void addCookie(String name,
                      String value)
Creates a session cookie (means that cookie will expire when the browser is closed). The path used for the cookie is the context path. If a null name is specified, this method does nothing.

Parameters:
name - The name of the cookie
value - The value of the cookie.
See Also:
addCookie(String, String, int)

addCookie

public void addCookie(String name,
                      String value,
                      int maxAge)
Tries to create a cookie on the client browser. The path used for the cookie is the context path. If a null name is specified, this method does nothing.

Parameters:
name - The name of the cookie.
value - The value of the cookie.
maxAge - A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age when the cookie will expire, not the cookie's current age. The maxAge is in seconds.

addHeader

public void addHeader(Header header,
                      Object value)
Adds a response header with the given header and value. This method allows response headers to have multiple values.

Parameters:
header - The header.
value - The header value.
Since:
1.3.4
See Also:
addHeader(String, Object)

addHeader

public void addHeader(String name,
                      Object value)
Adds a response header with the given name and value. This method allows response headers to have multiple values.

Parameters:
name - The name of the header.
value - The header value.
Since:
1.3.4
See Also:
HttpServletResponse.addHeader(String, String)

disableBrowserCache

public void disableBrowserCache()
Tries to disables browser cache on current response. This method uses headers Header.ETAG, Header.LAST_MODIFIED, Header.EXPIRES, Header.PRAGMA and Header.CACHE_CONTROL.

See Also:
setLastModified(Date), setExpires(Date), setHeader(Header, Object), addHeader(Header, Object)

encodeRedirectURL

public String encodeRedirectURL(String url)

Invokes this method in order to obtain the redirect URL. Unless the specified URL starts with a protocol, it is considered context-absolute, and the context and servlet path is prepended so that URL encoding of session ID will work if needed.

This method is the same as encodeRedirectURL(url, true).

Parameters:
url - The URL to redirect to.
See Also:
encodeRedirectURL(String, boolean)

encodeRedirectURL

public String encodeRedirectURL(String url,
                                boolean includeServletPath)
Invokes this method in order to obtain the redirect URL. Unless the specified URL starts with a protocol, it is considered context-absolute, and the context is prepended so that URL encoding of session ID will work if needed.

Parameters:
url - The URL to redirect to.
includeServletPath - if true, the URL (if it doesn't starts with a protocol) will be prepended by the servlet path.
See Also:
getURL(boolean, boolean, boolean, boolean), encodeURL(String, boolean), HttpServletResponse.encodeRedirectURL(String)

encodeURL

public String encodeURL(String url)

Invokes this method in order to obtain the encoded URL. Unless the specified URL starts with a protocol, it is considered context-absolute, and the context and servlet path is prepended so that URL encoding of session ID will work if needed.

This method is the same as encodeURL(url, true).

Parameters:
url - The URL to redirect to.
See Also:
encodeURL(String, boolean)

encodeURL

public String encodeURL(String url,
                        boolean includeServletPath)
Invokes this method in order to obtain the encoded URL. Unless the specified URL starts with a protocol, it is considered context-absolute, and the context is prepended so that URL encoding of session ID will work if needed.

Parameters:
url - The URL to be encoded.
includeServletPath - if true, the URL (if it doesn't starts with a protocol) will be prepended by the servlet path.
See Also:
getURL(boolean, boolean, boolean, boolean), encodeRedirectURL(String, boolean), HttpServletResponse.encodeURL(String)

flash

public void flash(String name,
                  Object value)

This method sets an attribute into the session and then, into request in order to be displayed after a redirect. The request attribute name is flash, you can use it into your JSPs.This method is often used for confirmation messages after a POST action and before redirecting user to a view. The flash message will be cleared just after rendering a view.

The object stored into the session is a Map of flash's name as keys. Here is an example into JSP's: ${flash['notice']}

This map is cleared just after rendering view.

Since:
1.3.3
See Also:
renderView(String, String, String)

forwardRequest

public void forwardRequest(String path)
Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

Parameters:
path - a String specifying the pathname to the resource.
Throws:
RuntimeException - if a ServletException or an input/output exception occurred.
Since:
1.2
See Also:
ServletRequest.getRequestDispatcher(String), RequestDispatcher.forward(ServletRequest, ServletResponse)

getAction

public final ActionMapping getAction()

Returns the action mapped by current URL or null if there is no action (or no controller) matching current URL.

The common case when there is no action mapping current URL (in other words, when this method returns null) is when this Service object represents a Filter and its class has ExecuteIfNotFound annotation.


getCompleteURL

public URL getCompleteURL(boolean includeQueryString)
Returns the complete URL include host, port.

Parameters:
includeQueryString - if true, the returned URL will contain the query string.
Throws:
RuntimeException - if URL is malformed.
Since:
1.1
See Also:
getURL(boolean, boolean, boolean, boolean)

getCompleteURL

public URL getCompleteURL(Class<? extends Controller> controllerClass,
                          String methodName,
                          Object... extraInfos)
Returns the complete (with scheme and host) URL of the specified action. You need specify the action controller's class and its method name.

Parameters:
controllerClass - The class of a mapped controller.
methodName - The method name of the action.
extraInfos - The extra informations of the action path. First it is path patterns. Each specified extra info will replace ${string}, ${int} or ${all} patterns in the action path. If you specify more extra info than path pattern, your parameters will be added to the query string, one by one (only if your parameters are not null).
Throws:
MappingException - if controller is no registered or if it has no action with specified method's name.
NullPointerException - if specified controller class or method name is null.
Since:
1.6.4
See Also:
ActionMapping.getURL(Object[])

getContextPath

public String getContextPath()
Returns the portion of the request URI that indicates the context of the request. The context path always comes first in a request URI. The path starts with a "/" character but does not end with a "/" character. For servlets in the default (root) context, this method returns "". The container does not decode this string.

Returns:
A String specifying the portion of the request URI that indicates the context of the request
Since:
1.4.1
See Also:
HttpServletRequest.getContextPath()

getCookie

public Parameter getCookie(String name)
A convenience helper to extract a cookie value as a Parameter.

Parameters:
name - The cookie's name.
Returns:
A parameter containing cookie value or a Parameter with null as value if there is no cookie with specified name.

getCookies

public Map<String,Parameter> getCookies()
Returns a Map containing all of the Cookie objects the client sent with this request.

Returns:
an unmodifiable Map containing cookie names as keys and cookie values as map values.

getErrors

public Collection<ErrorMessage> getErrors()
Returns all errors into the current request.

Specified by:
getErrors in interface ErrorProducer
Overrides:
getErrors in class ErrorContainer
Since:
1.4

getHeader

public Parameter getHeader(Header header)

Returns the value of the specified request header. If the request did not include a header of the specified name, this method returns a Parameter with null as value.

If there are multiple headers with the same name, this method returns the first header in the request. The header name is case insensitive. You can use this method with any request header.

Since:
1.3.4
See Also:
getHeader(String), Header.toString()

getHeader

public Parameter getHeader(String name)

Returns the value of the specified request header. If the request did not include a header of the specified name, this method returns a Parameter with null as value.

If there are multiple headers with the same name, this method returns the first header in the request. The header name is case insensitive. You can use this method with any request header.

Parameters:
name - a String specifying the header.

getHeaders

public Map<String,Parameter> getHeaders()
Returns a map of all the header names and value this request contains. If the request has no headers, this method returns an empty map.


getHost

public String getHost()
Returns the host specified into the current request.

Since:
1.4.1

getLocale

public Locale getLocale()

Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.

If the client request doesn't provide an Accept-Language header, this method returns the default locale for the server.

Since:
1.1
See Also:
ServletRequest.getLocale()

getMethod

public final Method getMethod()
Returns the current HTTP method.


getOutputStream

public ServletOutputStream getOutputStream()
Returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data. Calling flush() on the ServletOutputStream commits the response. Either this method or getWriter() may be called to write the body, not both.

Throws:
RuntimeException - if an I/O error occurs.
See Also:
getWriter(), ServletResponse.getOutputStream()

getParam

public Parameter getParam(String name)

Returns the value of a request parameter. Request parameters are extra information sent with the request. Parameters are contained in the query string or posted form data.

You should only use this method when you are sure the parameter has only one value. If the parameter might have more than one value, use getParams(String). If you use this method with a multivalued parameter, the value returned is equal to the first value in the array returned by getParams(String).

If specified param's name doesn't exists, null isn't returns, A non-existant (Parameter.exists()) is returned, otherwise, its value will be trimmed.

Parameters:
name - a String specifying the name of the parameter
Throws:
RuntimeException - with the FileUploadException as cause if there are problems while reading/parsing the request or storing files (only with file upload requests).
See Also:
getParams(String)

getParamOrSessionAttr

public <T> T getParamOrSessionAttr(String paramName,
                                   String sessionAttr,
                                   T defaultValue)
Returns the parameter of specified name with specified default value or load it from session if not exists. This method also stores the parameter into the session for the next time (if request parameter is not specified).

Parameters:
paramName - The request parameter name.
sessionAttr - The session attribute name.
defaultValue - The default value if parameter doesn't exists in request and in session.
Since:
1.5
See Also:
getSessionAttribute(String, Object)

getParamOrSessionAttr

public <T> T getParamOrSessionAttr(String name,
                                   T defaultValue)
Returns the parameters of specified name with specified default value or load it from session if not exists. This method also stores the parameter into the session for the next time (if request parameter is not specified).

Parameters:
name - The name of the parameter in request and in session.
defaultValue - The default value if parameter doesn't exists in request and in session.
Since:
1.5
See Also:
getParamOrSessionAttr(String, String, Object)

getParams

public Map<String,Parameter> getParams()

Returns a Map of parameters of a request. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.

This method doesn't works with multiple parameters value, this method will only return the first selected value. Use getParams(String) instead.

Returns:
an unmodifiable Map containing parameter names as keys and parameter values as map values.
Throws:
RuntimeException - with the FileUploadException as cause if there are problems while reading/parsing the request or storing files (only with file upload requests).

getParams

public Collection<Parameter> getParams(String name)

Returns a Collection of parameters of a request. Request parameters are extra information sent with the request. Parameters are contained in the query string or posted form data. This method is often used with multiple selects.

If the parameter has a single value, the collection has a size of 1.

If specified param's name doesn't exists, an empty collection is returned is returned.

Collection.contains(Object) and Collection.containsAll(Collection) methods will work with String, Long,... parameters with the returned collection.

Parameters:
name - a String specifying the name of the parameter
Returns:
An unmodifiable Collection of parameters.
Throws:
RuntimeException - with the FileUploadException as cause if there are problems while reading/parsing the request or storing files (only with file upload requests).
See Also:
getParam(String)

getPathInfo

public final String getPathInfo()
Returns any extra path information associated with current URL. This method removes consecutive slashes and consecutive white-spaces (only one is preserved) on the specified path. This method also trims path and path parts (a part is a string between two slashes). Returned string will never ends with a slash but always starts with a slash.

See Also:
ServletParameters.getPathInfo(), HttpServletRequest.getPathInfo()

getPathInfoWithQueryString

public String getPathInfoWithQueryString()
Returns the path info with the query string after if present.

Since:
1.1
See Also:
getPathInfo(), getQueryString()

getPathParam

public Parameter getPathParam()
Returns the first variable part of the current path. Variable parts are identified thanks to ${string}, ${int} or ${all} patterns into path. If there is no action matching current URL, this method will return a Parameter with null as value. This method is equivalent to getPathParam(0).

See Also:
getPathParam(int)

getPathParam

public Parameter getPathParam(int index)
Returns the variable part of the current path. Variable parts are identified thanks to ${string}, ${int} or ${all} patterns into path. If there is no action matching current URL, this method will return a Parameter with null as value.

Parameters:
index - The index of the parameter into the path. For example first, ${string}, ${int} or ${all} pattern will be the index 0, the second: the index 1,...
See Also:
getAction(), getPathInfo(), ActionMapping.getPathParam(String, int)

getPort

public int getPort()
Returns the port of the request, it can be 8080, 80, etc. If the port is not specified into the request, the default port of the protocol is returned.

Since:
1.4.1
See Also:
getProtocol(), Protocol.getPort()

getProtocol

public Protocol getProtocol()
Returns the current protocol of the request.

Since:
1.4.1
See Also:
Protocol.getProtocol(String), ServletRequest.getScheme()

getPublicURL

public String getPublicURL(String path)
Returns the public URL of specified path.

Parameters:
path - The path of your document inside the public path.
Returns:
The public URL of specified path without possible context path. Returned path always starts with a / (if not empty).
Since:
1.5.1
See Also:
Engine.getPublicPath()

getQueryString

public String getQueryString()
Returns the query string or the empty string if missing.

Since:
1.1
See Also:
HttpServletRequest.getQueryString()

getRemoteAddress

public String getRemoteAddress()
Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.

Since:
1.3.5
See Also:
ServletRequest.getRemoteAddr()

getRequest

public final HttpServletRequest getRequest()
Returns the current request.


getRequestAttribute

public Object getRequestAttribute(String name)
Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.

Since:
1.1
See Also:
ServletRequest.getAttribute(String)

getResponse

public final HttpServletResponse getResponse()
Returns the current response.


getResponseLocale

public Locale getResponseLocale()

Returns the locale specified for this response using the setLocale(Locale) method.

Calls made to setLocale after the response is committed have no effect. If no locale has been specified, the container's default locale is returned.

Since:
1.1
See Also:
ServletResponse.getLocale()

getSession

public HttpSession getSession()
Returns the current session associated with this request, or if the request does not have a session, creates one.

See Also:
HttpServletRequest.getSession()

getSessionAttribute

public <T> T getSessionAttribute(String name,
                                 T defaultValue)
Returns the session attribute of specified name. If the attribute doesn't exists in session, this stores the default value and returns it.

Parameters:
name - The attribute's name.
defaultValue - The default value if not found.
Returns:
The attribute stored into session or the default value if missing.
Since:
1.5
See Also:
getSession(), HttpSession.getAttribute(String), HttpSession.setAttribute(String, Object)

getUploadedFile

public FileItem getUploadedFile()
                         throws FileUploadSizeException

A convenience helper to extract the unique uploaded file by the client browser. This method returns null if there is no file uploaded by the current request. If the request sends multiple files, this method will returns one of those files but not necessary the first one. You also need to use getUploadedFile(String) method instead.

The default size limit of a file upload request is 2 megabytes (2097152 bytes). If the request exceeds this limit a FileUploadSizeException is thrown.

If you want to change this limit, override getFileUpload() method and customize the returned value or call getFileUpload().setSizeMax(yourLimit) method. Don't forget to invoke setSizeMax method before trying to obtain parameters or uploaded files, otherwise your limit will be ignored.

Returns:
The first file uploaded by the client browser or null if there is no file uploaded by current request.
Throws:
FileUploadSizeException - if the request exceeds the size of the file upload limit.
RuntimeException - with the FileUploadException as cause if there are problems while reading/parsing the request or storing files (only with file upload requests).
Since:
1.0
See Also:
getFileUpload(), getUploadedFile(String), getUploadedFiles()

getUploadedFile

public FileItem getUploadedFile(String name)
                         throws FileUploadSizeException

Returns a FileItem uploaded from the client browser or null if there is no file represented by the specified name.

The default size limit of a file upload request is 2 megabytes (2097152 bytes). If the request exceeds this limit a FileUploadSizeException is thrown.

If you want to change this limit, override getFileUpload() method and customize the returned value or call getFileUpload().setSizeMax(yourLimit) method. Don't forget to invoke setSizeMax method before trying to obtain parameters or uploaded files, otherwise your limit will be ignored.

Throws:
FileUploadSizeException - if the request exceeds the size of the file upload limit.
RuntimeException - with the FileUploadException as cause if there are problems while reading/parsing the request or storing files (only with file upload requests).
Since:
1.0
See Also:
getFileUpload(), getUploadedFile(), getUploadedFiles()

getUploadedFiles

public Map<String,FileItem> getUploadedFiles()
                                      throws FileUploadSizeException

Returns a map of uploaded files by the client browser.

The default size limit of a file upload request is 2 megabytes (2097152 bytes). If the request exceeds this limit a FileUploadSizeException is thrown.

If you want to change this limit, override getFileUpload() method or call getFileUpload().setSizeMax(yourLimit) method. Don't forget to invoke setSizeMax method before trying to obtain parameters or uploaded files, otherwise your limit will be ignored.

Returns:
an unmodifiable map of uploaded files. An empty map will be returned if there is no uploaded file.
Throws:
FileUploadSizeException - if the request exceeds the size of the file upload limit.
RuntimeException - with the FileUploadException as cause if there are problems while reading/parsing the request or storing files (only with file upload requests).
Since:
1.0
See Also:
getUploadedFile(String)

getURL

public String getURL()
A convenience helper to retrieve the current relative URL with the servlet path but without path info and query string. This is the same as getURL(true, true, false, false). This method does not add session ID, use encodeRedirectURL(String) or encodeURL(String) instead.

See Also:
getURL(boolean, boolean, boolean, boolean)

getURL

public String getURL(boolean includeQueryString)
A convenience helper to retrieve the current relative URL. The URL will contain the servlet path and the path info.

Parameters:
includeQueryString - if true, the returned URL will contain the query string.
See Also:
getURL(boolean, boolean, boolean, boolean)

getURL

public String getURL(boolean relative,
                     boolean includeServletPath,
                     boolean includePathInfo,
                     boolean includeQueryString)
Retrieves the current URL.

Parameters:
relative - if false the returned URL will contain the protocol, the protocol and the port.
includeServletPath - if true, the returned URL will contain servlet path. This parameter will be considered as true if includePathInfo parameter is true.
includePathInfo - if true, the returned URL will contain path info (i.e: the path after context path, including the servlet path).
includeQueryString - if true, the returned URL will contain the query string (i.e: the part after ? char).
See Also:
HttpServletRequest.getRequestURL(), HttpServletRequest.getServletPath(), HttpServletRequest.getPathInfo(), HttpServletRequest.getQueryString()

getURL

public String getURL(Class<? extends Controller> controllerClass,
                     String methodName,
                     Object... extraInfos)
Returns the URL of the specified action. You need specify the action controller's class and its method name.

Parameters:
controllerClass - The class of a mapped controller.
methodName - The method name of the action.
extraInfos - The extra informations of the action path. First it is path patterns. Each specified extra info will replace ${string}, ${int} or ${all} patterns in the action path. If you specify more extra info than path pattern, your parameters will be added to the query string, one by one (only if your parameters are not null).
Throws:
MappingException - if controller is no registered or if it has no action with specified method's name.
NullPointerException - if specified controller class or method name is null.
See Also:
ActionMapping.getURL(Object[])

getWriter

public PrintWriter getWriter()
Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified as described in getCharacterEncoding (i.e., the method just returns the default value ISO-8859-1), getWriter updates it to ISO-8859-1. Calling flush() on the PrintWriter commits the response. Either this method or getOutputStream() may be called to write the body, not both.

Throws:
RuntimeException - if an input or output exception occurred.
See Also:
getOutputStream(), ServletResponse.getWriter()

hasParam

public boolean hasParam(String name)
Determines whether a parameter exists.

Parameters:
name - The parameter's name

isAjaxRequest

public boolean isAjaxRequest()
Determines if request is an Ajax request. If X-Requested-With HTTP header is sent and has value XMLHttpRequest, this method returns true.


isHttpsRequest

public boolean isHttpsRequest()
Determines if current request is an HTTPS request.

Since:
1.4.1
See Also:
getProtocol(), Protocol.HTTPS, ServletRequest.getScheme()

isLocalRequest

public boolean isLocalRequest()
Determines if the the remove address is a local address. This method checks IPV4 and IPV6 local addresses.

Since:
1.3.5
See Also:
getRemoteAddress()

paginate

public Pagination paginate(Collection items)
Creates a new pagination object and set it into current request. The current page index is retrieved from the page parameter.

Parameters:
items - The items to paginate.
Returns:
The created pagination.
Since:
1.7.1
See Also:
paginate(Collection, Integer)

paginate

public Pagination paginate(Collection items,
                           Integer maxItemCountPerPage)
Creates a new pagination object and set it into current request.Items count is determined from Collection.size() method. The current page index is retrieved from the page parameter.

Parameters:
items - The items to paginate.
maxItemCountPerPage - The max visible item count in a page.
Returns:
The created pagination.
Since:
1.7.1
See Also:
paginate(Integer, Integer)

paginate

public Pagination paginate(Integer itemCount)
Creates a new pagination object and set it into current request. The current page index is retrieved from the page parameter.

Parameters:
itemCount - The item count.
Returns:
The created pagination.
Since:
1.7
See Also:
paginate(Integer, Integer)

paginate

public Pagination paginate(Integer itemCount,
                           Integer maxItemCountPerPage)
Creates a new pagination object and set it into current request. The pagination object has name pagination into the request. The current page index is retrieved from the page parameter.

Parameters:
itemCount - The item count.
maxItemCountPerPage - The max visible item count in a page.
Returns:
The created pagination.
Since:
1.7
See Also:
Pagination.Pagination(int), Pagination.setPageIndex(Integer)

print

public void print(Object... objects)
Prints specified objects on servlet output stream. This method uses String.valueOf(Object) method.

Since:
1.5
See Also:
getWriter()

println

public void println(Object... objects)
Prints specified objects on servlet output stream and a end of line delimiter after each object. If no object are specified, this method only prints the line delimiter. This method uses String.valueOf(Object) method.

Since:
1.5
See Also:
getWriter()

redirect

public void redirect(Class<? extends Controller> controllerClass,
                     String methodName,
                     Object... extraInfos)
Redirect to the specified action. This method is safe even if you change your action's or controller's path because it use the method name.

Parameters:
controllerClass - The class of a mapped controller.
methodName - The method name of the action.
extraInfos - The extra informations of the action path. First it is path patterns. Each specified extra info will replace ${string}, ${int} or ${all} patterns in the action path. If you specify more extra info than path pattern, your parameters will be added to the query string, one by one (only if your parameters are not null).
Throws:
MappingException - if controller is no registered or if it has no action with specified method's name or if action method is not Method.GET.
NullPointerException - if specified controller class or method name is null.
See Also:
getURL(Class, String, Object[])

redirect

public void redirect(String url)

Invoke this when your doPost method is done with business logic, and therefore needs to redirect the user's browser to a result page accessed through a regular HTTP GET. Unless the URL starts with a protocol, it is considered context-absolute, and the context and servlet path is prepended so that URL encoding of session ID will work if needed.

This method is the same as redirect(url, true).

Parameters:
url - The URL to redirect to.
Throws:
RuntimeException - if an input or output exception occurred.
See Also:
redirect(String, boolean)

redirect

public void redirect(String url,
                     boolean includeServletPath)
Invoke this when your doPost method is done with business logic, and therefore needs to redirect the user's browser to a result page accessed through a regular HTTP GET. Unless the URL starts with a protocol, it is considered context-absolute, and the context is prepended so that URL encoding of session ID will work if needed.

Parameters:
url - The URL to redirect to.
includeServletPath - if true, the URL (if it doesn't starts with a protocol) will be prepended by the servlet path.
Throws:
RuntimeException - if an input or output exception occurred.
See Also:
encodeRedirectURL(String, boolean), HttpServletResponse.sendRedirect(String)

redirect

public void redirect(URL url)
Invoke this in order to redirect the user's browser to the specified URL.

Parameters:
url - The URL to redirect to.
Throws:
RuntimeException - if an input or output exception occurs.
NullPointerException - if specified url is null.
See Also:
redirect(String)

redirectToPublic

public void redirectToPublic(String path)
Makes a redirection to a public document.

Parameters:
path - The path of the public document.
Since:
1.5.1
See Also:
getPublicURL(String)

removeCookie

public void removeCookie(String name)
Tries to remove the cookie identified by the specified name.

Parameters:
name - The cookie's name.

removeCookies

public void removeCookies(boolean keepSessionCookie)
Tries to remove all cookies currently stored on the user's browser.

Parameters:
keepSessionCookie - true in order to keep the session cookie called JSESSIONID, false otherwise.

removeSessionAttributes

public void removeSessionAttributes(String... exclusions)
Removes all attributes into the current user session.

Parameters:
exclusions - Attributes to exclude from removal.
See Also:
HttpSession.removeAttribute(String), getSession()

renderFile

public void renderFile(File file)
                throws IOException
Renders specified file to the output stream. A buffer of 8192 bytes is used. The content type is determined from the extension of the given file. If the content-type has been specified before, it will not be changed.

Parameters:
file - The file to render.
Throws:
NullPointerException - if specified file is null.
IOException - if an I/O error occurs.
Since:
1.6.5
See Also:
renderFile(File, String)

renderFile

public void renderFile(File file,
                       String contentType)
                throws IOException
Renders specified file to the output stream. A buffer of 8192 bytes is used. This method also change the Content-Length header (if not specified before).

Parameters:
file - The file to render.
contentType - The content type of the response. If null is given, application/octet-stream is used.
Throws:
IOException - if an I/O error occurs.
Since:
1.6.7
See Also:
renderStream(InputStream), setContentType(String), Header.CONTENT_LENGTH

renderFile

public void renderFile(String file)
                throws IOException
Renders specified file to the output stream. A buffer of 8192 bytes is used. The content type is determined from the extension of the given file. If the content-type has been specified before, it will not be changed.

Parameters:
file - The file to render.
Throws:
IOException - if an I/O error occurs.
Since:
1.6.5
See Also:
renderFile(File)

renderFile

public void renderFile(String file,
                       String contentType)
                throws IOException
Renders specified file to the output stream. A buffer of 8192 bytes is used. This method also change the Content-Length header (if not specified before).

Parameters:
file - The file to render.
contentType - The content type of the response. If null is given, application/octet-stream is used.
Throws:
IOException - if an I/O error occurs.
Since:
1.6.7
See Also:
renderFile(File, String)

renderFragment

public void renderFragment()

Invoke this to forward control to the view's JSP. Fragments is assumed to be stored in the /WEB-INF/views directory and to be stored in files with a .jspf extension.

The path is determined from the current action method name preceded by the controller's name. The returned path always starts with a slash but never ends with a slash. All uppercase letters are preceded by an underscore and converted to lowercase. The name of the controller represents the directory, the name of the action method, the file.

Example: for an action with method list obtained in controller UsersAccounts. The path of the fragment is: users_accounts/list. The full path will be /WEB-INF/views/users/account/list.jspf.

Throws:
IllegalStateException - if the current action is null.
RuntimeException - if a ServletException or an input/output exception occurred.
Since:
1.5.2
See Also:
getAction(), ActionMapping.getViewPath(), renderFragment(String)

renderFragment

public void renderFragment(Class<? extends Controller> controllerClass,
                           String methodName)

Invoke this to forward control to the view's JSP. Fragments are assumed to be stored in the /WEB-INF/views directory (and directories below), and to be stored in files with a .jspf extension.

The path is determined from the current action method name preceded by the controller's name. The returned path always starts with a slash but never ends with a slash. All upper case letters are preceded by an underscore and converted to lower case. The name of the controller represents the directory, the name of the action method, the file.

Example: for an action with method list obtained in controller UsersAccounts. The path of the fragment is: users_accounts/list. The full path will be /WEB-INF/views/users_accounts/list.jsp.

Throws:
MappingException - if controller is no registered or if it has no action with specified method's name.
NullPointerException - if specified class or method name is null.
Since:
1.5.2
See Also:
renderFragment(String)

renderFragment

public void renderFragment(String name)

Invoke this to forward control to the view's JSP. Fragments are assumed to be stored in the /WEB-INF/views directory (and directories below), and to be stored in files with a .jspf extension.

Since:
1.5.2
See Also:
FRAGMENTS_EXTENSION, VIEWS_PATH, renderFragment(String, String, String)

renderFragment

public void renderFragment(String name,
                           String directory,
                           String extension)
Invoke this to forward control to the view's JSP. This method can be overridden to customize views path and directory for other renderFragment methods.

Parameters:
name - The JSP fragment's name.
directory - The JSP fragment directory.
extension - The file extension of the fragment (including the dot).
Since:
1.5.2
See Also:
forwardRequest(String)

renderStream

public void renderStream(InputStream in)
                  throws IOException
Renders specified stream to the output buffer. This method doesn't closes the specified stream. A buffer of 8192 (8 KB) bytes is used.

Parameters:
in - The stream to render.
Throws:
NullPointerException - if specified stream is null.
IOException - if an I/O error occurs.
Since:
1.6.5
See Also:
renderStream(InputStream, int)

renderStream

public void renderStream(InputStream in,
                         int bufferSize)
                  throws IOException
Renders specified stream to the output buffer. This method doesn't closes the specified stream. This method also set Header#CACHE_CONTROL header to private, must-revalidate.

Parameters:
in - The stream to render.
bufferSize - The size of the buffer to read data from.
Throws:
NullPointerException - if specified stream is null.
IllegalArgumentException - if specified buffer's size is negative or 0.
IOException - if an I/O error occurs.
Since:
1.6.5
See Also:
getOutputStream(), Header.CACHE_CONTROL

renderView

public void renderView()

Invoke this to forward control to the view's JSP. View is assumed to be stored in the /WEB-INF/views directory and to be stored in files with a .jsp extension.

The path is determined from the current action method name preceded by the controller's name. The returned path always starts with a slash but never ends with a slash. All upper case letters are preceded by an underscore and converted to lower case. The name of the controller represents the directory, the name of the action method, the file.

Example: for an action with method list obtained in controller UsersAccounts. The path of the view is: users_accounts/list. The full path will be /WEB-INF/views/users/account/list.jsp.

Throws:
IllegalStateException - if the current action is null.
RuntimeException - if a ServletException or an input/output exception occurred.
See Also:
getAction(), ActionMapping.getViewPath(), renderView(String)

renderView

public void renderView(Class<? extends Controller> controllerClass,
                       String methodName)

Invoke this to forward control to the view's JSP. Views are assumed to be stored in the /WEB-INF/views directory (and directories below), and to be stored in files with a .jsp extension.

The path is determined from the current action method name preceded by the controller's name. The returned path always starts with a slash but never ends with a slash. All uppercase letters are preceded by an underscore and converted to lowercase. The name of the controller represents the directory, the name of the action method, the file.

Example: for an action with method list obtained in controller UsersAccounts. The path of the view is: users_accounts/list. The full path will be /WEB-INF/views/users_accounts/list.jsp.

Throws:
MappingException - if controller is no registered or if it has no action with specified method's name.
NullPointerException - if specified class or method name is null.
Since:
1.5.2

renderView

public void renderView(String name)
Invoke this to forward control to the view's JSP. Views are assumed to be stored in the /WEB-INF/views directory (and directories below), and to be stored in files with a .jsp extension.

Parameters:
name - The view's name, including potential directories.
Throws:
RuntimeException - if a ServletException or an input/output exception occurred.
See Also:
VIEWS_EXTENSION, VIEWS_PATH, renderView(String, String, String)

renderView

public void renderView(String name,
                       String directory,
                       String extension)
Invoke this to forward control to the view's JSP. This method can be overrided to customize views path and directory for other renderView methods.

Parameters:
name - The view's name.
directory - The view directory.
extension - The file extension of the view (including the dot).
See Also:
forwardRequest(String)

responseContainsHeader

public boolean responseContainsHeader(Header header)
Determines if the current response contains specified header.

Since:
1.6.7
See Also:
responseContainsHeader(String)

responseContainsHeader

public boolean responseContainsHeader(String header)
Determines if the current response contains specified header.

Since:
1.6.7

sendError

public void sendError(Code code,
                      String message)
Sends an error response to the client using the specified status.

Parameters:
code - The error code.
message - The message to display.
Throws:
NullPointerException - if specified code is null.
See Also:
sendError(int, String), Code.getCode()

sendError

public void sendError(int code,
                      String message)

Sends an error response to the client using the specified status. The server defaults to creating the response to look like an HTML-formatted server error page containing the specified message, setting the content type to "text/html", leaving cookies and other headers unmodified. If an error-page declaration has been made for the web application corresponding to the status code passed in, it will be served back in preference to the suggested message parameter.

If the response has already been committed, this method throws an IllegalStateException. After using this method, the response should be considered to be committed and should not be written to.

Parameters:
code - The error status code.
message - The descriptive message.
Throws:
IllegalStateException - if the response was committed.
RuntimeException - if an input or output exception occurred.
See Also:
HttpServletResponse.sendError(int, String)

sendError

public void sendError(String message)
A convenience helper to send a 500 error (Code.INTERNAL_SERVER_ERROR) to the client browser.

Since:
1.3.4
See Also:
sendError(int, String)

sendNotFound

public void sendNotFound()
Sends a 404 (Code.NOT_FOUND) error to the client's browser.

See Also:
sendError(int, String)

sendPermissionDenied

public void sendPermissionDenied()
Sends "Permission Denied" (403 HTTP code) to the client browser.

Since:
1.3.1
See Also:
sendError(int, String), Code.FORBIDDEN

setContentType

public void setContentType(String type)
Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification, for example, text/html;charset=UTF-8. The response's character encoding is only set from the given content type if this method is called before getWriter is called.

Parameters:
type - a String specifying the MIME type of the content
See Also:
ServletResponse.setContentType(String)

setExpires

public void setExpires(Date date)
Sets the expires header to specified date. If null is given, the current date is used.

Since:
1.6.2
See Also:
setHeader(String, Object), System.currentTimeMillis()

setHeader

public void setHeader(Header header,
                      Object value)
Sets a response header with the given enumeration and value. If the header had already been set, the new value overwrites the previous one.

Parameters:
header - The header.
value - The header value.
Since:
1.3.4
See Also:
setHeader(String, Object), Header.toString()

setHeader

public void setHeader(String name,
                      Object value)
Sets a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. This method uses String.valueOf(Object) on specified value.

Parameters:
name - The name of the header.
value - The header value.
Since:
1.2
See Also:
HttpServletResponse.setHeader(String, String), String.valueOf(Object)

setLastModified

public void setLastModified(Date date)
Sets the last modified header to specified date. If null is given, the current date is used.

Since:
1.3.4
See Also:
setHeader(String, Object), System.currentTimeMillis()

setLocale

public void setLocale(Locale locale)
Sets the locale of the response, if the response has not been committed yet.

Since:
1.1
See Also:
ServletResponse.setLocale(Locale)

setOutputFilename

public void setOutputFilename(String filename)
Sets the filename of the output. This method is useful for forcing download of the output instead of rendering it.

Parameters:
filename - The file's name to download.
Since:
1.7
See Also:
setHeader(Header, Object), Header.CONTENT_DISPOSITION

setOutputFilename

public void setOutputFilename(String filename,
                              String contentType)
Sets the filename of the output. This method is useful for forcing download of the output instead of rendering it. This method also changes the content-type of the response.

Parameters:
filename - The file's name to download.
contentType - The content-type of the response.
Since:
1.7
See Also:
setOutputFilename(String), setContentType(String)

setRequestAttribute

public void setRequestAttribute(String name,
                                Object value)
A convenience helper to set an attribute into the current request. This method is useful for obtaining variables in view from controller.

Parameters:
name - The name of the attribute.
value - The value of the attribute.
Throws:
NullPointerException - if specified name is null.
See Also:
ServletRequest.setAttribute(String, Object)

toString

public String toString()
Provides a string representation of this Service object.

Overrides:
toString in class Object
Returns:
The name of this Service.
See Also:
ServiceMapping.getName()

TagLib documentation