home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book Home Java Servlet Programming Search this book

Appendix B. HTTP Servlet API Quick Reference

The javax.servlet.http package allows development of servlets that support the HTTP protocol. While the core functionality in the javax.servlet package provides everything necessary for web development, the specialized classes in this package automate many otherwise tedious tasks. For example, the abstract HttpServlet class includes support for different HTTP request methods and headers. The HttpServletRequest and HttpServletResponse interfaces allow additional direct interaction with the web server, while HttpSession provides built-in session tracking functionality. The Cookie class allows you to quickly set up and process HTTP cookies, and the HttpUtils class does the same for query strings. Figure B-1 shows the class hierarchy of the javax.servlet.http package.

figure

Figure B-1. The javax.servlet.http package

Cookie

Synopsis

Class Name: javax.servlet.http.Cookie
Superclass: java.lang.Object
Immediate Subclasses: None
Interfaces Implemented: java.lang.Cloneable
Availability: New as of Servlet API 2.0; found in JSDK 2.0, JWS 1.1; an earlier version previously in sun.* hierarchy

Description

The Cookie class provides an easy way for servlets to read, create, and manipulate HTTP-style cookies, which allow servlets to store small amounts of data on the client. Cookies are generally used for session tracking or storing small amounts of user-specific configuration information. For more information, consult Chapter 7, "Session Tracking".

A servlet uses the getCookies() method of HttpServletRequest to retrieve cookies submitted as part of a client request. The addCookie() method of HttpServletResponse sends a new cookie to the browser. Because cookies are set using HTTP headers, addCookie() must be called before any output is sent to the client.

The original Servlet API 1.0 lacked this Cookie class, although the Java Web Server included a Sun-specific sun.servlet.util.Cookie class that worked in roughly the same manner. The only significant difference is that the retrieval and creation methods were static components of the Cookie class itself, rather than being part of the HttpServletRequest and HttpServletResponse interfaces.

Class Summaries

public class Cookie implements java.lang.Cloneable {
  // Constructors
  public Cookie(String name, String value);

 // Instance Methods
  public Object clone();
  public String getComment();
  public String getDomain();
  public int getMaxAge();
  public String getName();
  public String getPath();
  public boolean getSecure();
  public String getValue();
  public int getVersion();
  public void setComment(String purpose);
  public void setDomain(String pattern);
  public void setMaxAge(int expiry);
  public void setPath(String uri);
  public void setSecure(boolean flag);
  public void setValue(String newValue);
  public void setVersion(int v);
}

Constructors

Cookie()

public Cookie(String name, String value)
Description
Constructs a new cookie with an initial name and value. The rules for valid names and values are given in Netscape's Cookie Specification and RFC 2109.

Instance Methods

clone()

public Object clone()
Description
Overrides the standard clone() method to return a copy of this object (a duplicate cookie).

getComment()

public String getComment()
Description
Returns the comment associated with the cookie.

getDomain()

public String getDomain()
Description
Returns the domain limitation associated with this cookie.

getMaxAge()

public int getMaxAge()
Description
Returns the maximum age allowed for this cookie.

getPath()

public String getPath()
Description
Returns the path limitation for this servlet.

getSecure()

public boolean getSecure()
Description
Returns true if this cookie requires a secure connection, false otherwise.

getName()

public String getName()
Description
Returns the name of this cookie.

getValue()

public String getValue()
Description
Returns the value of this cookie, in string format.

getVersion()

public int getVersion()
Description
Returns the version of this cookie.

setComment()

public void setComment(String purpose)
Description
Sets the comment field of the cookie. A comment describes the intended purpose of a cookie. A web browser may choose to display this text to the user. Comments are not supported by Version 0 cookies.

setDomain()

public void setDomain(String pattern)
Description
Specifies a domain restriction pattern. A domain pattern specifies the servers that should see a cookie. By default, cookies are returned only to the host that saved them. Specifying a domain name pattern overrides this. The pattern must begin with a dot and must contain at least two dots. A pattern matches only one entry beyond the initial dot. For example, ".foo.com" is valid and matches www.foo.com and upload.foo.com but not www.upload.foo.com. For details on domain patterns, see Netscape's Cookie Specification and RFC 2109.

setMaxAge()

public void setMaxAge(int expiry)
Description
Specifies the maximum age of the cookie in seconds before it expires. A negative value indicates the default, that the cookie should expire when the browser exits. A zero value tells the browser to delete the cookie immediately.

setPath()

public void setPath(String uri)
Description
Specifies a path for the cookie, which is the subset of URIs to which a cookie should be sent. By default, cookies are sent to the page that set the cookie and to all the pages in that directory or under that directory. For example, if /servlet/CookieMonster sets a cookie, the default path is "/servlet". That path indicates the cookie should be sent to /servlet/Elmo and to /servlet/subdir/BigBird--but not to the /Oscar.html servlet alias or to any CGI programs under /cgi-bin. A path set to "/" causes a cookie to be sent to all the pages on a server. A cookie's path must be such that it includes the servlet that set the cookie.

setSecure()

public void setSecure(boolean flag)
Description
The secure flag indicates whether the cookie should be sent only over a secure channel, such as SSL. This value defaults to false.

setValue()

public void setValue(String newValue)
Description
Assigns a new value to a cookie. With Version 0 cookies, values should not contain the following: whitespace, brackets and parentheses, equals signs, commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may not behave the same way on all browsers.

setVersion()

public void setVersion(int v)
Description
Servlets can send and receive cookies formatted to match either Netscape persistent cookies (Version 0) or the newer, somewhat experimental, RFC 2109 cookies (Version 1). Newly constructed cookies default to Version to maximize interoperability.
HttpServlet

Synopsis

Class Name: javax.servlet.http.HttpServlet
Superclass: javax.servlet.GenericServlet
Immediate Subclasses: None
Interfaces Implemented: javax.servlet.Servlet, java.io.Serializable
Availability: Servlet API 1.0 and later

Description

HttpServlet is an abstract class that serves as a framework for developing HTTP (World Wide Web) servlets. The public service() method dispatches requests to an HTTP-specific, protected service() method. You may either extend the HTTP-specific service() method (which is then used to handle all types of HTTP requests) or leave the default service method alone and allow it to dispatch requests to particular handler functions for each HTTP submission type: doGet(), doPost(), and so on. Because the default HTTP servlet implementation handles dispatching to these methods, if you override the protected service() method, you must either handle the dispatching manually or not use the handler functions for HTTP request methods.

Class Summary

public abstract class HttpServlet extends javax.servlet.GenericServlet 
  implements javax.servlet.Servlet, java.io.Serializable {
  // Constructors
  public HttpServlet();

  // Public Instance Methods
  public void service(ServletRequest req, ServletResponse res) 
    throws ServletException, IOException;

  // Protected Instance Methods
  protected void doDelete(HttpServletRequest req, HttpServletResponse res) 
    throws ServletException, IOException;                   // New in 2.0
  protected void doGet(HttpServletRequest req, HttpServletResponse res) 
    throws ServletException, IOException; 
  protected void doOptions(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException;                   // New in 2.0
  protected void doPost(HttpServletRequest req,  HttpServletResponse res) 
    throws ServletException, IOException;
  protected void doPut(HttpServletRequest req, HttpServletResponse res) 
    throws ServletException, IOException;                   // New in 2.0
  protected void doTrace(HttpServletRequest req, HttpServletResponse res) 
    throws ServletException, IOException;                   // New in 2.0
  protected long getLastModified(HttpServletRequest req);
  protected void service(HttpServletRequest req, HttpServletResponse res) 
    throws ServletException, IOException;
}

Constructors

HttpServlet()

public HttpServlet()
Description
The default constructor does nothing. Because you cannot be sure of how and when classes will be loaded, it is not advisable to override this constructor to perform startup tasks. Use init() instead.

Public Instance Methods

service()

public void service(ServletRequest req, ServletResponse res) 
  throws ServletException, IOException
Description
This service() method handles dispatching requests to the protected, HTTP-specific service() method and cannot be overridden without disabling dispatching to the doXXX() methods.

Protected Instance Methods

doDelete()

protected void doDelete(HttpServletRequest req, HttpServletResponse res) 
  throws ServletException, IOException
Description
The default service() implementation in HttpServlet dispatches all HTTP DELETE requests to this method. Servlets implement this method to handle DELETE requests. The default implementation returns an HTTP BAD_REQUEST error. This method was introduced in the Servlet API 2.0.

doGet()

protected void doGet(HttpServletRequest req, HttpServletResponse res) 
  throws ServletException, IOException
Description
The default service() implementation in HttpServlet dispatches all HTTP GET requests to this method. Servlets implement this method to handle GET requests. The default implementation returns an HTTP BAD_REQUEST error.

doPost()

protected void doPost(HttpServletRequest req, HttpServletResponse res) 
  throws ServletException, IOException
Description
The default service() implementation in HttpServlet dispatches all HTTP POST requests to this method. Servlets implement this method to handle POST requests. The default implementation returns an HTTP BAD_REQUEST error.

doPut()

protected void doPut(HttpServletRequest req, HttpServletResponse res) 
  throws ServletException, IOException
Description
The default service() implementation in HttpServlet dispatches all HTTP PUT requests to this method. Servlets implement this method to handle PUT requests. The default implementation returns an HTTP BAD_REQUEST error. See RFC 2068 at http://www.ietf.org/rfc/rfc2068.txt for more on HTTP PUT requests. This method was introduced in the Servlet API 2.0.

doOptions()

protected void doOptions(HttpServletRequest req, HttpServletResponse res) 
  throws ServletException, IOException
Description
The default service() implementation in HttpServlet dispatches all HTTP OPTIONS requests to this method. The default implementation determines which options are supported and returns an appropriate header. For example, if a servlet overrides doGet() and doPost(), the browser is informed that GET, POST, HEAD, TRACE, and OPTIONS are supported. There is almost never any reason to override this method. This method was introduced in the Servlet API 2.0.

doTrace()

protected void doTrace(HttpServletRequest req, HttpServletResponse res) 
  throws ServletException, IOException
Description
The default service() implementation in HttpServlet dispatches all HTTP TRACE requests to this method. The default implementation returns a message listing all of the headers sent in the TRACE request. There is almost never any reason to override this method. This method was introduced in the Servlet API 2.0.

getLastModified()

protected long getLastModified(HttpServletRequest req)
Description
Returns the date and time (expressed as milliseconds since midnight, January 1, 1970 GMT) that the content produced by the servlet was last modified. Negative values indicate that the time is not known. The default implementation returns -1. Called by servers in support of conditional HTTP GET requests. See Chapter 4, "Retrieving Information", for more information.

service()

protected void service(HttpServletRequest req, HttpServletResponse res) 
  throws ServletException, IOException
Description
The public service() method dispatches requests to this service() method. This method handles dispatching requests to doGet(), doPost(), and the other handler functions based on the type of request. If this method is overridden, no handlers are called.
HttpServletRequest

Synopsis

Interface Name: javax.servlet.http.HttpServletRequest
Superinterface: javax.servlet.ServletRequest
Immediate Subinterfaces: None
Implemented By: None
Availability: Servlet API 1.0 and later

Description

HttpServletRequest extends the basic ServletRequest class, providing additional functionality for HTTP (World Wide Web) servlets. It includes support for cookies and session tracking and access to HTTP header information. HttpServletRequest also parses incoming HTTP form data and stores it as servlet parameters.

The server passes an HttpServletRequest object to the service method of an HttpServlet.

Certain methods in this interface have suffered from documentation and implementation inconsistencies. Discrepancies have been noted where possible.

Interface Declaration

public interface HttpServletRequest extends javax.servlet.ServletRequest {
  // Methods
  public abstract String getAuthType();
  public abstract Cookie[] getCookies();                    // New in 2.0
  public abstract long getDateHeader(String name);
  public abstract String getHeader(String name);
  public abstract Enumeration getHeaderNames();
  public abstract int getIntHeader(String name);
  public abstract String getMethod();
  public abstract String getPathInfo();
  public abstract String getPathTranslated();
  public abstract String getQueryString();
  public abstract String getRemoteUser();
  public abstract String getRequestedSessionId();           // New in 2.0
  public abstract String getRequestURI();
  public abstract String getServletPath();
  public abstract HttpSession getSession(boolean create);   // New in 2.0
  public abstract boolean isRequestedSessionIdFromCookie(); // New in 2.0
  public abstract boolean isRequestedSessionIdFromUrl();    // New in 2.0
  public abstract boolean isRequestedSessionIdValid();      // New in 2.0
}

Methods

getAuthType()

public abstract String getAuthType()
Description
Returns the servlet's authentication scheme or null if the servlet was not protected by an access control mechanism. Possible schemes are "BASIC", "DIGEST", and "SSL". Same as the CGI variable AUTH_TYPE.

getCookies()

public abstract Cookie[] getCookies()
Description
Returns an array of Cookie objects that contains all the cookies sent by the browser as part of the request or null if no cookies were sent. This method was introduced in the Servlet API 2.0.

getDateHeader()

public abstract long getDateHeader(String name)
Description
Returns the value of the named header as a long value that represents a Date (the number of milliseconds since midnight, January 1, 1970, GMT) or -1 if the header was not sent as part of the request. The name is case insensitive. Throws an IllegalArgumentException when called on a header whose value cannot be converted to a Date. This method is useful for handling headers like Last-Modified and If-Modified-Since.

getHeader()

public abstract String getHeader(String name)
Description
Returns the value of the named header as a String or null if the header was not sent as part of the request. The name is case insensitive. This method can retrieve all header types.

getHeaderNames()

public abstract Enumeration getHeaderNames()
Description
Returns the names of all the headers a servlet can access as an Enumeration of Strings or an empty Enumeration if there were no headers. Some servlet implementations may not allow headers to be accessed in this way, in which case this method returns null.

getIntHeader()

public abstract int getIntHeader(String name)
Description
Returns the value of the named header as an int or -1 if the header was not sent as part of the request. The name is case insensitive. Throws a NumberFormatException when called on a header with a value that cannot be converted to an int.

getMethod()

public abstract String getMethod()
Description
Returns the HTTP method used to make the request. Example methods include "GET", "POST", and "HEAD". The same as the CGI variable REQUEST_METHOD. The HttpServlet implementation of service() uses this method when dispatching requests.

getPathInfo()

public abstract String getPathInfo()
Description
Returns the extra path information associated with the request or null if none was provided. The same as the CGI variable PATH_INFO.

getPathTranslated()

public abstract String getPathTranslated()
Description
Returns the extra path information translated to a file system path or null if there was no extra path information. The path returned does not necessarily point to an existing file or directory. The same as the CGI variable PATH_TRANSLATED. This method has been known to not function properly in some servlet runners.

getQueryString()

public abstract String getQueryString()
Description
Returns the query string from the request's URL. This value is the same as the CGI variable QUERY_STRING. Because HttpServletRequest parses this string into a set of servlet parameters available through getParameter(), most servlets can ignore this method.

getRemoteUser()

public abstract String getRemoteUser()
Description
Returns the name of the user making the request as a String or null if access to the servlet was not restricted. The same as the CGI variable REMOTE_USER. This generally requires that the user has logged in using HTTP authentication. There is no comparable method to directly retrieve the remote user's password.

getRequestedSessionId()

public abstract String getRequestedSessionId()
Description
This method returns the session ID specified by the client. This may not be the actual session identifier currently in use--for example, if the session expired before the request occurred, the server creates a new session ID and uses that one instead. This method was introduced in the Servlet API 2.0.

getRequestURI()

public abstract String getRequestURI()
Description
Returns the Universal Resource Identifier (URI) of the request. This is the resource requested by the client in the first line of its HTTP request, with the query string removed. For normal HTTP servlets, the request URI is the request URL minus the scheme, host, port, and query string but including extra path information. Early versions of the Servlet API defined and implemented this method in different ways. When writing code that depends on this method, make sure you know what you're actually getting.

getServletPath()

public abstract String getServletPath()
Description
Returns the part of the URI that refers to the servlet. It does not include any extra path information or the query string. This is the same as the CGI variable SCRIPT_NAME.

getSession()

public abstract HttpSession getSession(boolean create)
Description
Returns the current session associated with the user making the request. If the user has no current valid session, this method creates one if create is true or returns null if create is false. To ensure the session is properly maintained, this method should be called at least once before any output is written to the response. Servlets not using session tracking may ignore this method. This method was introduced in the Servlet API 2.0.

isRequestedSessionIdFromCookie()

public abstract boolean isRequestedSessionIdFromCookie()
Description
Returns true if the client submitted a session identifier via a cookie, false otherwise. This method was introduced in the Servlet API 2.0.

isRequestedSessionIdFromUrl()

public abstract boolean isRequestedSessionIdFromUrl()
Description
Returns true if the requested session ID was submitted via a rewritten URL, false otherwise. This method was introduced in the Servlet API 2.0.

isRequestedSessionIdValid()

public abstract boolean isRequestedSessionIdValid()
Description
Returns true if the session requested by the client is a valid session and is therefore the session currently in use. For new sessions and expired sessions, it returns false. This method was introduced in the Servlet API 2.0.
HttpServletResponse

Synopsis

Interface Name: javax.servlet.http.HttpServletResponse
Superinterface: javax.servlet.ServletResponse
Immediate Subinterfaces: None
Implemented By: None
Availability: Servlet API 1.0 and later

Description

HttpServletResponse extends the ServletResponse class to allow manipulation of HTTP protocol-specific data, including response headers and status codes. It also defines a series of constants that represent various HTTP status codes and includes helper functions for session tracking operations.

Interface Declaration

public interface HttpServletResponse extends javax.servlet.ServletResponse {
  // Constants
  public static final int SC_ACCEPTED;
  public static final int SC_BAD_GATEWAY;
  public static final int SC_BAD_REQUEST;
  public static final int SC_CONFLICT;
  public static final int SC_CREATED;
  public static final int SC_CONTINUE;                      // New in 2.0
  public static final int SC_FORBIDDEN;
  public static final int SC_GATEWAY_TIMEOUT;               // New in 2.0
  public static final int SC_GONE;                          // New in 2.0
  public static final int SC_HTTP_VERSION_NOT_SUPPORTED;    // New in 2.0
  public static final int SC_INTERNAL_SERVER_ERROR;
  public static final int SC_LENGTH_REQUIRED;               // New in 2.0
  public static final int SC_METHOD_NOT_ALLOWED;            // New in 2.0
  public static final int SC_MOVED_PERMANENTLY;
  public static final int SC_MOVED_TEMPORARILY;
  public static final int SC_MULTIPLE_CHOICES;              // New in 2.0
  public static final int SC_NO_CONTENT;
  public static final int SC_NON_AUTHORITATIVE_INFORMATION; // New in 2.0
  public static final int SC_NOT_ACCEPTABLE;                // New in 2.0
  public static final int SC_NOT_FOUND;
  public static final int SC_NOT_IMPLEMENTED;
  public static final int SC_NOT_MODIFIED;
  public static final int SC_OK;
  public static final int SC_PARTIAL_CONTENT;               // New in 2.0
  public static final int SC_PAYMENT_REQUIRED;              // New in 2.0
  public static final int SC_PRECONDITION_FAILED;           // New in 2.0
  public static final int SC_PROXY_AUTHENTICATION_REQUIRED; // New in 2.0
  public static final int SC_REQUEST_ENTITY_TOO_LARGE;      // New in 2.0
  public static final int SC_REQUEST_TIMEOUT;               // New in 2.0
  public static final int SC_REQUEST_URI_TOO_LONG;          // New in 2.0
  public static final int SC_RESET_CONTENT;                 // New in 2.0
  public static final int SC_SEE_OTHER;                     // New in 2.0
  public static final int SC_SERVICE_UNAVAILABLE;
  public static final int SC_SWITCHING_PROTOCOLS;           // New in 2.0
  public static final int SC_UNAUTHORIZED;
  public static final int SC_UNSUPPORTED_MEDIA_TYPE;        // New in 2.0
  public static final int SC_USE_PROXY;                     // New in 2.0

  // Methods
  public abstract void addCookie(Cookie cookie);            // New in 2.0
  public abstract boolean containsHeader(String name);
  public abstract String encodeRedirectUrl(String url);     // New in 2.0
  public abstract String encodeUrl(String url);             // New in 2.0
  public abstract void sendError(int sc) throws IOException;
  public abstract void sendError(int sc, String msg) throws IOException;
  public abstract void sendRedirect(String location) throws IOException;
  public abstract void setDateHeader(String name, long date);  
  public abstract void setHeader(String name, String value);
  public abstract void setIntHeader(String name, int value);
  public abstract void setStatus(int sc);
  public abstract void setStatus(int sc, String sm);
}

Constants:

Appendix C, "HTTP Status Codes", contains complete descriptions of all the SC_XXX status codes.

Methods

addCookie()

public abstract void addCookie(Cookie cookie)
Description
Adds the specified cookie to the response. Additional cookies can be added with repeated calls to addCookie(). Because cookies are sent using HTTP headers, they should be added to the response before sending any content. Browsers are required to accept only 20 cookies per site, 300 total per user, and they can limit each cookie's size to 4096 bytes.

containsHeader()

public abstract boolean containsHeader(String name)
Description
Returns true if the named header has already been set, false if not.

encodeRedirectUrl()

public abstract String encodeRedirectUrl(String url)
Description
Returns the specified URL encoded (rewritten) to include the session ID. If encoding is not needed or not supported, the method leaves the URL unchanged. The rules used to decide when and how to encode a URL are server-specific. This method may use different rules than encodeUrl(). To enable session tracking, all URLs passed to the sendRedirect() method should be run through this method. Note that this method employs a different capitalization scheme than getRequestURL() and getRequestURI().

encodeUrl()

public abstract String encodeUrl(String url)
Description
Returns the specified URL encoded (rewritten) to include the session ID. If encoding is not needed or not supported, the method leaves the URL unchanged. The rules used to decide when and how to encode a URL are server-specific. To enable session tracking, all URLs emitted by a servlet should be run through this method. Note that this method employs a different capitalization scheme than getRequestURL() and getRequestURI().

sendError()

public abstract void sendError(int sc) throws IOException 
public abstract void sendError(int sc, String msg) throws IOException
Description
These methods are similar to setStatus(), except that they are used when the status code indicates an error during the handling of the request. A server may give these methods different treatment than setStatus(). This method should be called before sending any content.

sendRedirect()

public abstract void sendRedirect(String location) throws IOException
Description
Redirects the response to the specified location, automatically setting the status code and Location header. The location must be an absolute URL, (including "http://"). The default implementaion also writes a short response body that contains a hyperlink to the location, to support browers without redirect capabilities. Consequently, do not write your own response body when using this method.

setDateHeader()

public abstract void setDateHeader(String name, long date)
Description
Sets the value of the named header as a String specifying a particular date and time. The method accepts the date value as a long that represents the number of milliseconds since midnight, January 1, 1970, GMT. If the header has already been set, the new value overwrites the previous one.

setHeader()

public abstract void setHeader(String name, String value)
Description
Sets the value of the named header as a String. The name is case insensitive (as with all header-related methods). If the header has already been set, the new value overwrites the previous one. This method can set any header type. Headers should always be set before sending any content.

setIntHeader()

public abstract void setIntHeader(String name, int value)
Description
Sets the value of the named header as an int. If the header has already been set, the new value overwrites the previous one.

setStatus()

public abstract void setStatus(int sc)
public abstract void setStatus(int sc, String sm)
Description
Sets the HTTP status code. The code can be specified using a numeric value or by using the SC_XXX codes defined within HttpServletResponse. You can optionally specify a custom error message; otherwise, the server uses the default message for that code, if any. The status should be set before sending any content.
HttpSession

Synopsis

Interface Name: javax.servlet.http.HttpSession
Superinterface: None
Immediate Subinterfaces: None
Implemented By: None
Availability: New as of the Servlet API 2.0; found in JSDK 2.0, JWS 1.1

Description

The HttpSession interface provides a mechanism for identifying return visitors to a web site. For a detailed introduction to session tracking, see Chapter 7, "Session Tracking". The HttpSession interface itself allows servlets to view and manipulate session-specific information, such as creation time and the unique session identifier. It also includes methods to bind objects to the session for later retrieval, allowing "shopping cart" and other applications to hold onto data

A servlet obtains an HttpSession object from the getSession() method of HttpServletRequest. Specific session behavior, such as the amount of idle time before a session is destroyed, depends on the server.

While any object can be bound to a session, lots of high-traffic servlets binding large objects to their sessions will impose a heavy resource burden on the server. With most implementations, this can be alleviated by binding only objects that implement the java.io.Serializable interface (this includes all of the data type objects in the core Java API). Some servers have the ability to write Serializable objects to disk to save memory. Unserializable objects, such as java.sql.Connection, must be retained in memory.

Interface Declaration

public interface HttpSession {
  // Methods
  public abstract long getCreationTime();
  public abstract String getId();
  public abstract long getLastAccessedTime();
  public abstract HttpSessionContext getSessionContext();
  public abstract Object getValue(String name);
  public abstract String[] getValueNames();
  public abstract void invalidate();
  public abstract boolean isNew();
  public abstract void putValue(String name, Object value);
  public abstract void removeValue(String name);
}

Methods

getCreationTime()

public abstract long getCreationTime()
Description
Returns the time at which the session was created, as a long representing the number of milliseconds since midnight, January 1, 1970, GMT. Throws an IllegalStateException if the session is invalid.

getId()

public abstract String getId()
Description
Returns the unique String identifier assigned to this session. The structure of the ID is implementation dependent. For example, a Java Web Server ID might be something like HT04D1QAAAAABQDGPM5QAAA. Throws an IllegalStateException if the session is invalid.

getLastAccessTime()

public abstract long getLastAccessedTime()
Description
Returns the time at which the client last sent a request associated with this session, as a long representing the number of milliseconds since midnight, January 1, 1970, GMT. Throws an IllegalStateException if the session is invalid.

getSessionContext()

public abstract HttpSessionContext getSessionContext()
Description
Returns the context in which the session is bound. See HttpSessionContext for more information. Throws an IllegalStateException if the session is invalid.

getValue()

public abstract Object getValue(String name)
Description
Returns the object bound in the session under the specified name or null if there is no matching binding. Throws an IllegalStateException if the session is invalid.

getValueNames()

public abstract String[] getValueNames()
Description
Returns an array containing the names of all objects bound to this session or an empty (zero length) array if there are no bindings. Throws an IllegalStateException if the session is invalid. Note that unlike most similar methods (getParameterNames(), getInitParameterNames(), getServletNames(), etc.), this method does not return an Enumeration. (No, we don't know why either.)

invalidate()

public abstract void invalidate()
Description
Causes the session to be immediately invalidated. All objects stored in the session are unbound. Throws an IllegalStateException if the session is already invalid.

isNew()

public abstract boolean isNew()
Description
Returns whether the session is new. A session is considered new if it has been created by the server but the client has not yet acknowledged joining the session. For example, if a server supports only cookie-based sessions and a client has completely disabled the use of cookies, calls to getSession() always return new sessions. Throws an IllegalStateException if the session is invalid.

putValue()

public abstract void putValue(String name, Object value)
Description
Binds the specified object value under the specified name in the session. Any existing binding with the same name is replaced. Throws an IllegalStateException if the session is invalid.

removeValue()

public abstract void removeValue(String name)
Description
Removes the object bound to the specified name or does nothing if there is no binding. Throws an IllegalStateException if the session is invalid.
HttpSessionBindingEvent

Synopsis

Class Name: javax.servlet.http.HttpSessionBindingEvent
Superclass: java.util.EventObject
Immediate Subclasses: None
Interfaces Implemented: None
Availability: New as of the Servlet API 2.0; found in JSDK 2.0, JWS 1.1

Description

An HttpSessionBindingEvent is passed to an HttpSessionBindingListener when the listener object is bound to or unbound from a session.

Class Summary

public class HttpSessionBindingEvent extends java.util.EventObject {
  // Constructors
  public HttpSessionBindingEvent(HttpSession session, String name);

  // Instance Methods
  public String getName();
  public HttpSession getSession();
}

Constructors

HttpSessionBindingEvent()

public HttpSessionBindingEvent(HttpSession session, String name)
Description
Constructs a new HttpSessionBindingEvent using the session being bound and the name that this object is being assigned (this is the same name passed to the putValue() method of HttpSession). Servlet programmers should never need to use this constructor.

Instance Methods

getName()

public String getName()
Description
Returns the name this object has been assigned within the session.

getSession()

public HttpSession getSession()
Description
Returns the session this object is being bound to or unbound from.
HttpSessionBindingListener

Synopsis

Interface Name: javax.servlet.http.HttpSessionBindingListener
Superinterface: java.util.EventListener
Immediate Subinterfaces: None
Implemented By: None
Availability: New as of the Servlet API 2.0; found in JSDK 2.0, JWS 1.1

Description

An object that implements HttpSessionBindingListener is notified via calls to valueBound() and valueUnbound() when it is bound to or unbound from an HttpSession. Among other things, this interface allows orderly cleanup session-specific resources, such as database connections.

Interface Declaration

public interface HttpSessionBindingListener extends java.util.EventListener {
  // Methods
  public abstract void valueBound(HttpSessionBindingEvent event);
  public abstract void valueUnbound(HttpSessionBindingEvent event);
}

Methods

valueBound()

public abstract void valueBound(HttpSessionBindingEvent event)
Description
Called when the listener is bound to a session.

valueUnbound()

public abstract void valueUnbound(HttpSessionBindingEvent event)
Description
Called when the listener is unbound from a session (including at session destruction).
HttpSessionContext

Synopsis

Interface Name:javax.servlet.http.HttpSessionContext
Superinterface: None
Immediate Subinterfaces: None
Implemented By: None
Availability: New as of the Servlet API 2.0; found in JSDK 2.0, JWS 1.1

Description

HttpSessionContext provides access to all of the currently active sessions on the server. This can be useful for servlets that weed out inactive sessions, display statistics, or otherwise share information. A servlet obtains an HttpSessionContext object from the getSessionContext() method of HttpSession.

Interface Declaration

public interface HttpSessionContext { 
  // Methods
  public abstract Enumeration getIds();
  public abstract HttpSession getSession(String sessionId);
}

Methods

getIds()

public abstract Enumeration getIds()
Description
Returns an Enumeration that contains the session IDs for all the currently valid sessions in this context. It returns an empty Enumeration if there are no valid sessions. The session IDs returned by getIds() should be held as a server secret because any client with knowledge of another client's session ID can, with a forged cookie or URL, join the second client's session.

getSession()

public abstract HttpSession getSession(String sessionId)
Description
Returns the session associated with the given session identifier. A list of valid session IDs can be obtained from the getIds() method.
HttpUtils

Synopsis

Class Name: javax.servlet.http.HttpUtils
Superclass: java.lang.Object
Immediate Subclasses: None
Interfaces Implemented: None
Availability: Servlet API 1.0 and later

Description

A container object for a handful of potentially useful HTTP-oriented methods.

Class Summary

public class HttpUtils {
  // Constructors
  public HttpUtils();

  // Class Methods
  public static StringBuffer getRequestURL(HttpServletRequest req);
  public static Hashtable parsePostData(int len, ServletInputStream in);
  public static Hashtable parseQueryString(String s);
}

Constructors

HttpUtils()

public HttpUtils()
Description
The default constructor does nothing.

getRequestURL()

public static StringBuffer getRequestURL(HttpServletRequest req)
Description
Reconstitutes the request URL based on information available in the HttpServletRequest object. Returns a StringBuffer that includes the scheme, server name, server port, and extra path information. The reconstituted URL should look almost identical to the URL used by the client. This method can be used for error reporting, redirecting, and URL creation. For applications that need to uniquely identify particular servlets, the getRequestURI() method of HttpServletRequest is generally a better choice.

parsePostData()

public static Hashtable parsePostData(int len, ServletInputStream in)
Description
Parses len characters of parameter data from a ServletInputStream (usually sent as part of a POST operation). Throws an IllegalArgumentException if the parameter data is invalid. Most servlets use getParameterNames(), getParameter(), and getParameterValues() instead of this method.

parseQueryString()

public static Hashtable parseQueryString(String s)
Description
Returns a Hashtable where the hashtable keys are the parameter names taken from the query string and each hashtable value is a String array that contains the parameter's decoded value(s). Throws an IllegalArgumentException if the query string is invalid. Most servlets use getParameterNames(), get-Parameter(), and getParameterValues() instead. It is not safe to use both.


Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.