Interfaces:
Servlet | ServletConfig | ServletContext |
ServletRequest | ServletResponse | SingleThreadModel |
Classes:
GenericServlet | ServletInputStream | ServletOutputStream |
Exceptions:
ServletException | UnavailableException |
Servlet:Interface
Defines the Life Cycle methods of a servlet: init, service and destroy
methods.
It also provides methods that allows servlets to get startup information,
about its server environment and also a method to provide to the server
a description about the servlet.
public abstract void destroy()
Cleans up whatever resources are being held
(e.g., memory, file handles, threads) and makes sure that any persistent
state is synchronized with the servlet's current in-memory state. The servlet
should be designed in such a way that all threads executing service method
complete by the time destroy is called.
public abstract ServletConfig getServletConfig()
Returns a servlet config object, which contains
any initialization parameters and startup configuration for this servlet.
It is the same servlet config object passed to the init method and the
init method should have stored it, so that this method could return.
public abstract String getServletInfo()
Returns a string containing information about
the servlet, such as its author, version, and copyright.
public abstract void init(ServletConfig) throws ServletException
Initializes the servlet. If the initialization
fails it should throw an UnavailableException and should never call System.exit()
method.
public abstract void service(ServletRequest, ServletResponse)
throws ServletException , IOException
Carries out a single request from the client.
The method implements a request-response paradigm. Servlets run in multi-threaded
servers. The servlet shoud be made thread-safe and synchronize access to
shared resources like network connections, servlet's class and instance
variables.
The interface is generally implemented by services of the server in order to pass configuration information to the servlet when it gets initialized. Servlets can also implement it so as to have an eay implementation of getting the servletContext:
Here is an implementation of getServletContext():
public ServletContext getServletContext() {
return getServletConfig().getServletContext();
}
This could be replaced by:
public ServletContext getServletContext() {
return getServletContext();
}
GenericServlet implements the ServletConfig.
Methods:
public abstract String getInitParameter(String)
Returns a string containing the value of the
named initialization parameter of the servlet, or null if the parameter
does not exist.
public abstract Enumeration getInitParameterNames()
Returns the names of the servlet's initialization
parameters as an enumeration of strings, or an empty enumeration
if there are no initialization parameters.
public abstract ServeltContext getServletContext()
Returns the context for the servlet.
The interface is implemented by the services of the server and used by the servlet to access information about its environment and also to log significant events. It is obtained by calling the getServletContext method on the ServletConfig passed on to the servlet at the time of the initialization.
Methods:
public abstract String getAttribute(String)
Returns the value of the named attribute of
the network service, or null if the attribute does not exist.
public abstract String getMimeType(String)
Returns the mime type of the specified file,
or null if not known.
public abstract String getRealPath(String)
Applies alias rules to the specified virtual
path and returns the corresponding real path.For example, in an HTTP
servlet, this method would resolve the path
against the HTTP service's docroot. Returns null if virtual paths are
not supported, or if the translation could
not be performed for any reason.
public abstract String getServerInfo()
Returns the name and version of the network
service under which the servlet is running. In an HTTP server this
value will be the same as the value of the
CGI variable SERVER_SOFTWARE
public abstract Servlet getServlet(String) throw ServletException
Returns the servlet of the specified name,
or null if not found.
This is a dangerous method to call because:
public abstract Enumeration getServlets()
Returns an enumeration of the Servlet objects
in this server. Deprecated.
public abstract void log(Exception, String)
Write the stacktrace and the given message
string to the servlet log file. The servlet log file is server specific
and
is normally an event log file.
public abstract void log(String)
Writes the given message string to the servlet
log file.
The Interface is used to provide data from the client to the servlet. The data includes parameter names and values, attributes, and an input stream. MIME bodies are either text or binary. If binary use getInputStream, else if text use getReader. Multipart MIME bodies are considered binary.
Methods:
public abstract String getAttribute(String)
Returns the value of the named attribute of
the request, or null if the attribute does not exist.
public abstract String getCharacterEncoding()
Returns the character set encoding for the
input of this request.
public abstract int getContentLength()
Returns the size of the request entity data,
or -1 if not known.
public abstract String getContentType()
Returns the Internet Media Type of the request
entity data, or null if not known.
public abstract ServletInputStream getInputStream() throws
IOException
Returns an input stream for reading binary
data in the request body.
public abstract String getParameter(String)
Returns a string containing the lone value
of the specified parameter, or null if the parameter does not exist.
For example it could return the value of the
specified query String Parameter or posted form.
public abstract String getParameterNames()
Returns the parameter names for this request
as an enumeration of strings, or an empty enumeration if there
are no parameters or the input stream is empty.
The input stream could be empty of all data had been read from
the input Stream returned by the method getInputStream.
public abstract Enumeration getParameterValues(String)
Returns the values of the specified parameter
for the request as an array of strings, or null if the named
parameter does not exist.
public abstract String getProtocol()
Returns the protocol and version of the request
as a string of the form <protocol>/<major
version>.<minor version>.
public abstract BufferedReader getReader()
Returns a buffered reader for reading text
in the request body.
public abstract String getRealPath(String)
Applies alias rules to the specified virtual
path and returns the corresponding real path, or null if the translation
can not be performed for any reason.
public abstract String getRemoteAddr()
Returns the IP address of the agent that sent
the request.
public abstract String getRemoteHost()
Returns the fully qualified host name of the
agent that sent the request.
public abstract String getScheme()
Returns the scheme of the URL used in this
request, for example "http", "https", or "ftp".
public abstract String getServerName()
Returns the host name of the server that received
the request.
public abstract int getServerPort()
Returns the port number on which this request
was received.
public abstract String getCharacterEncoding()
Returns the character set encoding used for
this MIME body.
public abstract ServletOutputStream getOutputStream() throws
IOException
Returns an output stream for writing binary
response data.
public abstract PrintWriter getWriter() throws IOException
Returns a print writer for writing formatted text responses.
public abstract void setContentLength(int)
Sets the content length for this response.
Must be called before calling getWriter or getOutputStream.
public abstract void setContentType(String)
Sets the content type for this response. Must
be called before calling getWriter or getOutputStream.
Defines a "single" thread model for servlet execution. This empty interface
allows servlet implementers to specify
how the system should handle concurrent calls to the same servlet.
If the target servlet is flagged with this interface, the servlet programmer
is guaranteed that no two threads will
execute concurrently the service method of that servlet. This guarantee
is ensured by maintaining a pool of servlet
instances for each such servlet, and dispatching each service call
to a free servlet.
In essence, if the servlet implements this interface, the servlet will
be thread safe.
The GenericServlet class implements the Servlet interface and, for convenience,
the ServletConfig interface. Servlet
developers typically subclass GenericServlet, or its descendent HttpServlet,
unless the servlet needs another class as
a parent. (If a servlet does need to subclass another class, the servlet
must implement the Servlet interface directly.
This would be necessary when, for example, RMI or CORBA objects act
as servlets.)
The GenericServlet class was created to make writing servlets easier.
It provides simple versions of the lifecycle
methods init and destroy, and of the methods in the ServletConfig interface.
It also provides a log method, from the
ServletContext interface. The servlet writer must override only the
service method, which is abstract. Though not
required, the servlet implementer should also override the getServletInfo
method, and will want to specialize the init
and destroy methods if expensive servlet-wide resources are to be managed.
Methods
public void destroy()
Destroys the servlet, cleaning up whatever
resources are being held, and logs the destruction in the servlet log
file.
public String getInitParameter(String)
Returns a string containing the value of the
named initialization parameter, or null if the requested parameter
does not exist.
public Enumeration getInitParameterNames()
Returns the names of the servlet's initialization
parameters as an enumeration of strings, or an empty
enumeration if there are no initialization
parameters.
public ServletConfig getServletConfig()
Returns a servletConfig object containing
any startup configuration information for this servlet.
public ServletContext getServletContext()
Returns a ServletContext object, which contains
information about the network service in which the servlet is
running.
pubic String getServletInfo()
Returns a string that contains information
about the servlet, such as its author, version, and copyright.
public void init(ServletConfig)
Initializes the servlet and logs the initialization.
public void log(String)
Writes the class name of the servlet and the
given message to the servlet log file.
public abstract void service(ServletRequest, ServletResponse)
throws ServletException, IOException
Carries out a single request from the client.
Use to read binary data from the client sent in say through HTTP POST or PUT methods. This getInputStream method of ServletRequest returns an instance of this class. The class provides a readLine method to read a line from the stream. Subclasses must provide implementation of the read method.
Methods:
public int readLine(byte[], int off, int len) throws IOException
Starting at the specified offset, reads into
the given array of bytes until all requested bytes have been read or a
'\n' is encountered, in which case the '\n'
is read into the array as well.
Returns the actual number of bytes read,
or -1 if the end of the stream is reached.
Use to write binary data as a response to the client. The getOutputStream returns an instance of this class. Subclass must implement the write method.
Methods:
All of the methods returns void and throws IOException
print(boolean)
Prints the boolean provided.
print(char)
Prints the character provided.
print(double)
Prints the double provided.
print(float)
Prints the float provided.
print(int)
Prints the integer provided.
print(long)
Prints the long provided.
print(String)
Prints the string provided.
println()
Prints a CRLF.
println(boolean)
Prints the boolean provided, followed by a
CRLF.
println(char)
Prints the character provided, followed by
a CRLF.
println(double)
Prints the double provided, followed by a
CRLF.
println(float)
Prints the float provided, followed by a CRLF.
println(int)
Prints the integer provided, followed by a
CRLF.
println(long)
Prints the long provided, followed by a CRLF.
println(String)
Prints the string provided, followed by a
CRLF.
This exception indicates that a servlet is unavailable. Servlets may
report this exception at any time, and the network
service running the servlet should behave appropriately. There are
two types of unavailability, and sophisticated
services will to deal with these differently:
Permanent unavailability. The servlet
will not be able to handle client requests until some administrative
action is taken to correct a servlet problem.
For example, the servlet might be misconfigured, or the state of
the servlet may be corrupted. Well written
servlets will log both the error and the corrective action which an
administrator must perform to let the servlet
become available.
Temporary unavailability. The servlet
can not handle requests at this moment due to a system-wide problem.
For example, a third tier server might not
be accessible, or there may be insufficient memory or disk storage
to handle requests. The problem may be self
correcting, such as those due to excessive load, or corrective
action may need to be taken by an administrator.
Network services may safely treat both types of exceptions as "permanent",
but good treatment of temporary
unavailability leads to more robust network services. Specifically,
requests to the servlet might be blocked (or
otherwise deferred) for a servlet-suggested amount of time, rather
than being rejected until the service itself restarts.
Constructors:
UnavailableException(int, Servlet, String)
Constructs a new exception with the specified
descriptive message, indicating that the servlet is temporarily
unavailable and giving an estimate of how
long it will be unavailable in seconds.
UnavailableException(Servlet, String)
Constructs a new exception with the specified
descriptive message, indicating that the servlet is permanently
unavailable.
Methods:
public Servlet getServlet()
Returns the servlet that is reporting its
unavailability.
public int getUnavailableSeconds()
Returns the amount of time the servlet expects
to be temporarily unavailable.
public boolean isPermanent()
Returns true if the servlet is "permanently"
unavailable, indicating that the service administrator must take
some corrective action to make the servlet
be usable.
Interfaces:
HttpServletRequest | HttpServletResponse | HttpSession |
HttpSessionBindingListener | HttpSessionContext |
Classes:
Cookie | HttpServlet |
HttpSessionBindingEvent | HttpUtils |
HttpServletRequest : Interface
This Interface extends the ServletRequest Interface. The interface allows HTTP-protocol specific header information to be accessed from the service method of the servlet.
Methods:
public abstract String getAuthType()
Gets the authentication scheme of this request.
public abstract Cookies[] getCookies()
Gets the array of cookies found in this request.
public abstract long getDateHeader(String)
Gets the value of the requested date header
field of this request. The case of the header name is ignored. If the
value cannot be converted to a Date then an
IllegalArgumentException is thrown.
public abstract String getHeader(String)
Gets the value of the requested header field
of this request. The case of the header name is ignored.
public abstract Enumeration getHeaderNames()
Gets the header names for this request.
public abstract int getIntHeader(String)
Gets the value of the specified integer header
field of this request. Throws a NumberFormatException if the
value cannot be converted to an integer. The
case of the Header name is ignored.
public abstract String getMethod()
Gets the HTTP method (for example, GET, POST,
PUT) with which this request was made.
public abstract String getPathInfo()
Gets any optional extra path information following
the servlet path of this request's URI, but immediately
preceding its query string.
public abstract String getPathTranslated()
Gets any optional extra path information following
the servlet path of this request's URI, but immediately
preceding its query string, and translates
it to a real path.
public abstract String getQueryString()
Gets any query string that is part of the
HTTP request URL.
public abstract String getRemoteUser()
Gets the name of the user making this request.
public abstract String getRequestedSessionId()
Gets the session id specified with this request.
This returned ID may be different from the one send in with the
request if the sent in one is the ID
of an invalid session in which case a new session ic created the new ID
is
returned.
public abstract String getRequestURI()
Gets, from the first line of the HTTP request,
the part of this request's URI that is to the left of any query
string. For example,
First line
of HTTP request
Return from getRequestURI
POST /some/path.html
HTTP/1.1
/some/path.html
GET http://foo.bar/a.html
HTTP/1.0
http://foo.bar/a.html
HEAD /xyz?a=b
HTTP/1.1
/xyz
To reconstruct a URL with a URL scheme and
host, use the method
javax.servlet.http.HttpUtils.getRequestURL,
which returns a StringBuffer.
public abstract String getServletPath()
Gets the part of this request's URI that refers
to the servlet being invoked.
public abstract HttpSession getSession(boolean)
Gets the current valid session associated
with this request, if create is false or, if necessary, creates a new
session for the request, if create is true.
public abstract boolean isRequestedSessionIdFromCookie()
Checks whether the session id specified by
this request came in as a cookie.
public abstract boolean isRequestedSessionIdFromUrl()
Checks whether the session id specified by
this request came in as part of the URL.
public abstract boolean isRequestedSessionIdValid()
Checks whether this request is associated
with a session that is valid in the current session context.
The interface defines all the status codes of HTTP-protocol as static
fields.
The class is used to manipulate header of the response to the client.
Important Static Fields:
SC_CONTINUE(100), SC_OK(200), SC_ACCEPTED(202), SC_NO_CONTENT(204), SC_MOVED_PERMANENTLY(301), SC_MOVED_TEMPORARILY(302), SC_BAD_REQUEST(400), SC_UNAUTHORIZED(401), SC_FORBIDDEN(403), SC_NOT_FOUND(404), SC_PROXY_AUTHENTICATION_REQUIRED(407), SC_CONFLICT(409), SC_GONE(410), SC_CONTENT_LENGTH(411), SC_UNSUPPORTED_MEDIA_TYPE(415), SC_INTERNAL_SERVER_ERROR(500), SC_SERVICE_UNAVAILABLE(503), SC_HTTP_VERSION_NOT_SUPPORTED(505) etc
Methods:
public abstract void addCookie(Cookie)
Adds the specified cookie to the response.
public abstract boolean containsHeader(String)
Checks whether the response message header
has a field with the specified name.
public abstract void encodeRedirectUrl(String)
Encodes the specified URL for use in the sendRedirect
method or, if encoding is not needed, returns the
URL unchanged. The implementation has
logic to determine whether to encode or not. The logic is different
from that of encodeURL method.
URLs used in sendRedirect must have been encoded using this method.
public abstract void encodeUrl(String)
Encodes the specified URL by including the
session ID in it, or, if encoding is not needed, returns the URL
unchanged. The implementation should include
logic to determine whether encoding is required or not. For
example if the browser supports cookies and
sever can set cookies to the client browser, then encoding is
not needed.
All URLs emitted from the servlet must go through
this method, otherwise URL rewriting cannot be done if the
browser does not support cookies.
public abstract void sendError(int) throws IOException
Sends an error response to the client using
the specified status code and a default message.
public abstract void sendError(int, String) throws IOException
Sends an error response to the client using
the specified status code and descriptive message. The message is
sent as the body of an html page with a default
header.
public abstract void sendRedirect(String URL) throws IOException
Sends a temporary redirect response to the
client using the specified redirect location URL. The URL must
be absolute (for example, https://hostname/path/file.html).
Relative URLs are not permitted here. The URL must
be encoded using the encodeRedirectURL method
to include the session ID.
public abstract void setDateHeader(String, long)
Adds a field to the response header with the
given name and date-valued field.
public abstract void setHeader(String, String)
Adds a field to the response header with the
given name and value.
public abstract void setIntHeader(String, int)
Adds a field to the response header with the
given name and integer value.
public abstract void setStatus(int)
Sets the status code for this response when
there is no error.
public abstract void setStatus(int, String)
Sets the return status code and message for
this response when there is no error. The message is sent as the
body of a html page to the client. The
page has a default header.
Session is an interface that is used to maintain state and user identity
across multiple page requests. The session is stored with the server.
A server considers a session to be new until it is joined by a client.
The isNew method returns true under the following conditions:
If the objects stored in the session implements the HttpSessionBindingListener then the object will be notified when it is bounded or unbounded from the session.
Methods:
All methods throws an IllegalArgumentException if the method is invoked when the session has been invalidated.
public abstract long getCreationTime()
Returns the time at which this session representation
was created, in milliseconds since midnight, January 1, 1970
UTC.
public abstract String getId()
Returns the identifier assigned to this session.
The session ID is a unique string created and maintained by the
HttpSessionContext.
public abstract long getLastAccessedTime()
Returns the last time the client sent a request
carrying the identifier assigned to the session. Application level
operation like getting and putting objects
into the object does not count as accessing.
public abstract HttpSesionContext getSessionContext()
Returns the context in which this session
is bound.
public abstract Object getValue(String)
Returns the object bound to the given name
in the session's application layer data. Returns null if there is no binding.
public abstract String[] getValueNames()
Returns an array of the names of all the application
layer data objects bound into the session.
public abstract void invalidate()
Causes this representation of the session
to be invalidated and removed from its context.
public abstract boolean isNew()
A session is considered to be "new" if it
has been created by the server, but the client has not yet acknowledged
joining the session. If the client does not
allows cookies to be set and the server allows only cookies-based clients,
the call to HttpServletRequest.getSession()
is always going to return a "new" session.
public abstract void putValue(String, Object)
Binds the specified object into the session's
application layer data with the given name. If the object implements the
HttpSessionBindingListener then the valueBound()
method will be invoked.
public abstract void removeValue(String)
Removes the object bound to the given name
in the session's application layer data. Does nothing if there is no
object bound to the given name. If the
object implements HttpSessionBindingListener then its valueUnbound()
method is called.
Methods:
public abstract void valueBound(HttpSessionBindingEvent)
Notifies the listener that it is being bound
into a session.
public abstract void valueUnbound(HttpSessionBindingEvent)
Notifies the listener that it is being unbound
from a session.
Methods:
public abstract Enumeration getIds()
Returns an enumeration of all of the session
IDs in this context.
public abstract HttpSession getSession(String)
Returns the session bound to the specified
session ID.
Cookie allows user agents (say web browser) to save some state associated with a user's web browsing. It can store information like user preferences, low-level security information etc.
Cookies are names and has a single value. It can have other attributes like comments, user, path and domain of hosts, maximum age, and version.
Cookies are set by the server through the cookies added to the servlet response using javax.servlet.http.HttpServletResponse.addCookie method. User agents are expected to support 20 cookies per host, with each cookie of 4 KB.
Cookies are sent in from the clients to those servers who set them by using the HTTP request. This can be extracted by using javax.servlet.http.HttpServletRequest.getCookies() method.
Constructor:
Cookie(String name, String value)
Defines a cookie with an initial name/value pair.
Methods:
public Object clone()
Returns a copy of this object.
public String getComment()
Returns the comment describing the purpose
of this cookie, or null if no such comment has been defined.
public String getDomain()
Returns the domain of this cookie.
public int getMaxAge()
Returns the maximum specified age of the cookie.
If it was not set it returns a negative value which is the default in
setMaxAge method.
public String getName()
Returns the name of the cookie. Once the cookie
has been set, the name may not be changed.
public String getPath()
Returns the prefix of all URLs for which this
cookie is targetted.
public boolean getSecure()
Returns the value of the 'secure' flag.
public String getValue()
Returns the value of the cookie.
public int getVersion()
Returns the version of the cookie.
public void setComment(String)
If a user agent (web browser) presents this
cookie to a user, the cookie's purpose will be described using this
comment.
public void setDomain(String)
This cookie should be presented only to hosts
satisfying this domain name pattern. In www.foo.com, .foo.com is the
domain. If the domain has been set to .foo.com
then host in that DNS zone (i.e www.foo.com and not a.b.foo.com)
could see the cookie. By default only host
that set the cookie can access the cookie.
public void setMaxAge(int)
Sets the maximum age of the cookie in seconds.
A negative value indicates the default: when user agent exits the
cookie is destroyed. A zero value mean delete the
cookie.
public void setPath(String)
This cookie should be presented only with
requests beginning with this URL. Unless a different path is set, all URLs
from the same "directory" as the one which
set the cookie, and in subdirectories, can all see the cookie.
public void setSecure(boolean)
Indicates to the user agent that the cookie
should only be sent using a secure protocol (https). The server from where
the cookie originate must use a secure protocol
to be able to set the cookie's value.
public void setValue(String)
Sets the value of the cookie.
public void setVersion(int)
Sets the version of the cookie protocol used
when this cookie saves itself.
The class extends GenericServlet and provides a base class for HTTP based servlets. The class is an abstract class and must be extended. Also the subclass must override at least one method. The following methods are generally overridden:
Methods:
protected void doDelete(HttpServletRequest, HttpServletResponse)
throws ServletException, IOException
Performs the HTTP DELETE operation; the default
implementation reports an HTTP BAD_REQUEST error.
protected void doGet(HttpServletRequest, HttpServletResponse)
throws ServletException, IOException
Performs the HTTP GET operation; the default
implementation reports an HTTP BAD_REQUEST error.
In general, the servlet implementor must write
the headers before the response data because the headers can be
flushed at any time after the data starts
to be written.
protected void doOptions(HttpServletRequest, HttpServletResponse)
throws ServletException, IOException
Performs the HTTP OPTIONS operation; the default
implementation of this method automatically determines
what HTTP Options are supported.
protected void doPost(HttpServletRequest, HttpServletResponse)
throws ServletException, IOException
Performs the HTTP POST operation; the default
implementation reports an HTTP BAD_REQUEST error.
protected void doPut(HttpServletRequest, HttpServletResponse)
throws ServletException, IOException
Performs the HTTP PUT operation; the default
implementation reports an HTTP BAD_REQUEST error.
protected void doTrace(HttpServletRequest, HttpServletResponse)
throws ServletException, IOException
Performs the HTTP TRACE operation; the default
implementation of this method causes a response with a
message containing all of the headers sent
in the trace request.
protected long getLastModified(HttpServletRequest)
Gets the time the requested entity was last
modified; the default implementation returns a negative number,
indicating that the modification time is unknown
and hence should not be used for conditional GET operations or
for other cache control operations as this
implementation will always return the contents.
Implementations supporting the GET request
should override this method to provide an accurate object
modification time. This makes browser and
proxy caches work more effectively, reducing the load on server and
network resources.
protected void service(HttpServletRequest, HttpServletResponse)
throws ServletException, IOException
This is an HTTP-specific version of the Servlet.service
method, which accepts HTTP specific parameters.
protected void service(HttpServletRequest, HttpServletResponse)
throws ServletException, IOException
Implements the high level Servlet.service
method by delegating to the HTTP-specific service method.
HttpSessionBindingEvent: Class
This event is communicated to a HttpSessionBindingListener whenever
the listener is bound to or unbound from a
HttpSession value.
The event's source is the HttpSession: binding occurs with a call to
HttpSession.putValue; unbinding occurs with a call to
HttpSession.removeValue.
Constructor:
HttpSessionBindingEvent(HttpSession, String)
Constructs a new HttpSessionBindingEvent
Methods:
public String getName()
Returns the name to which the object is being
bound or the name from which the object is being unbound.
public HttpSession getSession()
Returns the session into which the listener
is being bound or from which the listener is being unbound.
HttpUtils: Class
A collection of static utility methods useful for HTTP servlets.
Constructor:
HttpUtils()
Creates a HttpUtils object.
Methods:
public static StringBuffer getRequestURL(HttpServletRequest)
Reconstructs the URL used by the client used
to make the request. This returns schme such as http, httpds etc but
not the query string. As the result is a stringBuffer
the URL can be modified efficiently.
public static Hashtable parsePostData(int, ServletInputStream)
Parses FORM data that is posted to the server
using the HTTP POST method and the
application/x-www-form-urlencoded mime type.
public static Hashtable parseQueryString(String)
Parses a query string and builds a hashtable
of key-value pairs, where the values are arrays of strings.