GenericServlet | ||
|
||
GenericServlet provides a basic implementation of the Servlet interface for protocol-independent servlets. As a convenience, it also implements the ServletConfig interface. Most servlet developers subclass this class or HttpServlet, rather than implement the Servlet interface directly.
GenericServlet includes basic versions of the init() and destroy() methods, which perform basic setup and cleanup tasks, such as managing the server's ServletConfig object. It's good form for a servlet that overrides one of these methods to call the superclass version of the method. GenericServlet also includes a log() method that provides easy access to the logging functions from ServletContext.
The service() method is declared as abstract and must be overridden. Well written servlets also override getServletInfo().
public abstract class GenericServlet implements Servlet, ServletConfig, java.io.Serializable { // Constructors public GenericServlet(); // Instance Methods public void destroy(); public String getInitParameter(String name); public Enumeration getInitParameterNames(); public ServletConfig getServletConfig(); public ServletContext getServletContext(); public String getServletInfo(); public void init(ServletConfig config) throws ServletException; public void log(String msg); public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException; }
public GenericServlet()
- Description
- The default GenericServlet constructor does no work. Any servlet initialization tasks should be performed in init(), rather than in the constructor.
public void destroy()
- Description
- Called by the server before unloading the servlet. The default implementation logs the servlet's destruction in the server log file using the log() method. A servlet can override this method to save its state, free its resources, etc.
public String getInitParameter(String name)
- Description
- Returns the value of the named servlet initialization parameter or null if no matching parameter is found. From the ServletConfig interface.
public Enumeration getInitParameterNames()
- Description
- Returns all the servlet's init parameter names as an Enumeration of String objects or an empty Enumeration if no parameters exist. From the ServletConfig interface.
public ServletConfig getServletConfig()
- Description
- Returns the servlet's ServletConfig object. In practice, this method is rarely called by a GenericServlet because all of the ServletConfig methods are duplicated internally.
public ServletContext getServletContext()
- Description
- Returns the servlet's ServletContext object. From the ServletConfig interface.
public String getServletInfo()
- Description
- Returns a programmer-defined String that describes the servlet. A servlet should override this method and provide a customized identity string (e.g., "Al's Message Board Servlet v1.21"), but it is not required.
public void init(ServletConfig config) throws ServletException
- Description
- Called by the server after the servlet is first loaded and before the servlet's service() method is called. The default implementation of init() logs the servlet's initialization and stores the ServletConfig object for use by the methods in the ServletConfig interface. A servlet can override this method to perform additional one-time setup, creation of resources, etc. A servlet should always call the superclass implementation of init() using super.init(config) before executing any custom initialization code.
public void log(String msg)
- Description
- Writes the given message to a servlet log, usually an event log file. Both the output format and location are server-specific.
public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
- Description
- Called to handle a single client request. A servlet receives request information via a ServletRequest object and sends data back to the client via a ServletResponse object. This is the only method that must be overridden when extending GenericServlet. Because multiple service requests may execute concurrently, the service() method must be thread safe, unless the servlet also implements the SingleThreadModel interface.
Servlet | ||
|
||
All servlets implement the Servlet interface, either directly or by subclassing the GenericServlet or HttpServlet class. Most servlet developers find it easier to subclass one of the two existing servlet classes than to implement this interface directly. The interface declares the basic servlet functionality--initializing a servlet, handling a client request, and destroying a servlet.
public interface Servlet { // Methods public abstract void destroy(); public abstract ServletConfig getServletConfig(); public abstract String getServletInfo(); public abstract void init(ServletConfig config) throws ServletException; public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException; }
public abstract void destroy()
- Description
- Called when the server is preparing to unload a servlet. Used to clean up any outstanding resources (database connections, threads, file handles and so forth). The servlet programmer is responsible for making sure that any requests currently executing are allowed to finish.
public abstract ServletConfig getServletConfig()
- Description
- Returns the ServletConfig object passed to the init() method.
public abstract String getServletInfo()
- Description
- Returns a programmer-defined String that describes the servlet.
public abstract void init(ServletConfig config) throws ServletException
- Description
- Called by the server when the servlet is first loaded. The init() method should store the ServletConfig object for retrieval by getServletConfig(). When using either GenericServlet or HttpServlet, the default init() implementation handles this task. This method can also be used to perform any one-time actions required by the servlet, such as creating database connections. It is guaranteed to finish before any client requests are accepted.
public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
ServletConfig | ||
|
||
Servers use ServletConfig objects to pass initialization and context information to servlets. The initialization information generally consists of a series of initialization parameters (init parameters) and a ServletContext object, which provides information about the server environment. A servlet can implement Servlet-Config to allow easy access to init parameters and context information, as GenericServlet does.
public interface ServletConfig { // Methods public abstract String getInitParameter(String name); public abstract Enumeration getInitParameterNames(); public abstract ServletContext getServletContext(); }
public abstract String getInitParameter(String name)
- Description
- Returns the value of the named servlet initialization parameter or null if no matching parameter is found.
public abstract Enumeration getInitParameterNames()
- Description
- Returns the names of all the servlet's initialization parameters as an Enumeration of String objects or an empty Enumeration if no parameters exist.
public abstract ServletContext getServletContext()
ServletContext | ||
|
||
The ServletContext interface defines a set of methods that can be used to communicate with the server in a non-request-specific manner. This includes finding path information, accessing other servlets running on the server, and writing to the server log file. Different virtual servers may return different servlet contexts.
public interface ServletContext { // Methods public abstract Object getAttribute(String name); public abstract String getMimeType(String file); public abstract String getRealPath(String path); public abstract String getServerInfo(); public abstract Servlet getServlet(String name) throws ServletException; public abstract Enumeration getServletNames(); // New in 2.0 public abstract Enumeration getServlets(); // Deprecated public abstract void log(Exception exception, String msg); // New in 2.0 public abstract void log(String msg); }
public abstract Object getAttribute(String name)
- Description
- Returns the value of the named server attribute as an Object or null if the attribute does not exist. The attributes are server-dependent and allow web servers to provide servlets with information above and beyond that provided for by the base Servlet API. Attribute names should follow the same convention as package names. The package names java.* and javax.* are reserved for use by the Java Software division of Sun Microsystems (formerly known as JavaSoft), and com.sun.* is reserved for use by Sun Microsystems. See your server's documentation for a list of its attributes. Remember that servlets relying on server-specific attributes are not portable.
public abstract String getMimeType(String file)
- Description
- Returns the MIME type of the given file or null if it is not known. Some implementations return "text/plain" if the specified file does not exist. Common MIME types are "text/html", "text/plain", "image/gif", and "image/jpeg".
public abstract String getRealPath(String path)
- Description
- Returns the real file system path of any given "virtual path" or null if the translation cannot be performed. If the given path is "/", the method returns the document root for the servlet. If the given path is the same as the one returned by getPathInfo(), the method returns the same real path as would be returned by getPathTranslated(). There is no CGI counterpart.
public abstract String getServerInfo()
- Description
- Returns the name and version of the server software, separated by a forward slash (/). The value is the same as the CGI variable SERVER_SOFTWARE.
public abstract Servlet getServlet(String name) throws ServletException
- Description
- Returns the loaded servlet matching the given name or null if the servlet is not found. The specified name can be the servlet's registered name (e.g., "file") or class name (e.g., "com.sun.server.webserver .FileServlet"). The server maintains one servlet instance per name, so getServlet("file") returns a different servlet instance than get-Servlet("com.sun.server.webserver.FileServlet"). If the servlet implements SingleThreadModel, the server may return any instance of the servlet from the current pool. The server may--but is not required to--load the named servlet and execute its init() method if it was not already loaded. A ServletException is thrown if there is a problem during the load.
public abstract Enumeration getServletNames()
- Description
- Returns an Enumeration of the names of the servlet objects loaded in this context. When used with getServlet(String name), it can replace the deprecated getServlets(). This method was introduced in the Servlet API 2.0.
public abstract Enumeration getServlets() throws ServletException
- Description
- Returns an Enumeration of the Servlet objects loaded in this context. This method was deprecated in the Servlet API 2.0 in favor of getServletNames().
public abstract void log(Exception exception, String msg)
- Description
- Writes an exception's stack trace and a given message to a servlet log, usually an event log file. Both output format and location are server-specific. Notice the non-standard placement of the optional Exception parameter as the first parameter instead of the last. This method was introduced in the Servlet API 2.0.
public abstract void log(String msg)
ServletException | ||
|
A generic exception thrown by servlets encountering difficulties.
public class ServletException extends java.lang.Exception { // Constructors public ServletException(); // New in 2.0 public ServletException(String msg); }
public ServletException() public ServletException(String msg)
ServletInputStream | ||
|
||
Provides an input stream for reading binary data from a client request, including an efficient readLine() method for reading data one line at a time. A ServletInputStream is returned by the getInputStream() method of ServletRequest. A servlet that filters binary output from other sources generally gets its input via this stream.
public abstract class ServletInputStream extends java.io.InputStream { // Constructors protected ServletInputStream(); // Instance Methods public int readLine(byte b[], int off, int len) throws IOException; }
protected ServletInputStream()
public int readLine(byte b[], int off, int len) throws IOException
ServletOutputStream | ||
|
||
Provides an output stream for sending binary data back to a client. A servlet obtains a ServletOutputStream object from the getOutputStream() method of ServletResponse. Although it includes a range of print() and println() methods for sending text or HTML, the ServletOutputStream has been superseded by PrintWriter. It should be used only for sending binary data or with early servlet implementations built on the Servlet API 1.0.
If you subclass ServletOutputStream, you must provide an implementation of the write(int) method.
public abstract class ServletOutputStream extends java.io.OutputStream { // Constructors protected ServletOutputStream(); // Instance Methods public void print(boolean b) throws IOException; public void print(char c) throws IOException; public void print(double d) throws IOException; public void print(float f) throws IOException; public void print(int i) throws IOException; public void print(long l) throws IOException; public void print(String s) throws IOException; public void println() throws IOException; public void println(boolean b) throws IOException; public void println(char c) throws IOException; public void println(double d) throws IOException; public void println(float f) throws IOException; public void println(int i) throws IOException; public void println(long l) throws IOException; public void println(String s) throws IOException; }
protected ServletOutputStream()
- Description
- The default constructor does nothing.
public void print(boolean b) throws IOException public void print(char c) throws IOException public void print(double d) throws IOException public void print(float f) throws IOException public void print(int i) throws IOException public void print(long l) throws IOException public void print(String s) throws IOException
- Description
- Writes the given data to the client, without a trailing carriage return/line feed (CRLF).
public void println() throws IOException public void println(boolean b) throws IOException public void println(char c) throws IOException public void println(double d) throws IOException public void println(float f) throws IOException public void println(int i) throws IOException public void println(long l) throws IOException public void println(String s) throws IOException
ServletRequest | ||
|
||
A ServletRequest object encapsulates information about a single client request, including request parameters, implementation-specific attributes, and an input stream for reading binary data from the request body. ServletRequest can be subclassed to provide additional protocol-specific information. HttpServletRequest, for instance, includes methods to manipulate HTTP headers.
public interface ServletRequest { // Methods public abstract Object getAttribute(String name); public abstract String getCharacterEncoding(); // New in 2.0 public abstract int getContentLength(); public abstract String getContentType(); public abstract ServletInputStream getInputStream() throws IOException; public abstract String getParameter(String name); public abstract Enumeration getParameterNames(); public abstract String[] getParameterValues(String name); public abstract String getProtocol(); public abstract BufferedReader getReader() throws IOException;// New in 2.0 public abstract String getRealPath(String path); public abstract String getRemoteAddr(); public abstract String getRemoteHost(); public abstract String getScheme(); public abstract String getServerName(); public abstract int getServerPort(); }
public abstract Object getAttribute(String name)
- Description
- Returns the value of the named server-specific attribute as an Object, or null if the server does not support the named request attribute. Servers may use this method to provide servlets with custom information about a request. Attributes should follow the same conventions as package names, with the package names java.* and javax.* reserved for use by the Java Software division of Sun Microsystems (formerly known as JavaSoft), and com.sun.* reserved for use by Sun Microsystems. Remember that servlets that rely on server-specific request attributes are non-portable.
public abstract String getCharacterEncoding()
- Description
- Returns the charset encoding for the servlet's input stream, or null if not known. This method was introduced in the Servlet API 2.0. It does not exist in the Java Web Server 1.1.x.
public abstract int getContentLength()
- Description
- Returns the length, in bytes, of the content being sent via the input stream, or -1 if the length is not known (such as when there is no data). Equivalent to the CGI variable CONTENT_LENGTH.
public abstract String getContentType()
- Description
- Returns the media type of the content being sent via the input stream or null if the type is not known or there is no data. The same as the CGI variable CONTENT_TYPE.
public abstract ServletInputStream getInputStream() throws IOException
- Description
- Retrieves the input stream as a ServletInputStream object. Servlet-InputStream is a direct subclass of InputStream and can be treated identically to a normal InputStream, with the added ability to efficiently read input a line at a time into an array of bytes. This method should be used for reading binary input. It throws an IllegalStateException if getReader() has been called before on the request. The IllegalState-Exception does not need to be explicitly caught.
public abstract String getParameter(String name)
- Description
- Returns the value of the named parameter as a String. Returns null if the parameter does not exist, or an empty string if the parameter exists but without a value. The value is guaranteed to be in its normal, decoded form. If the parameter has multiple values, the value returned is server dependent. If there is any chance that a parameter has more than one value, you should use the getParameterValues() method instead. If the parameter information came in as encoded POST data, it may not be available if the POST data has already been manually read using the getReader() or getInputStream() methods. This method was deprecated momentarily in favor of getParameterValues(), but thanks to an overwhelming flood of support from the developer community, it has been restored in the Servlet API 2.0.
public abstract Enumeration getParameterNames()
- Description
- Returns all the parameter names as an Enumeration of String objects. It returns an empty Enumeration if the servlet has no parameters.
public abstract String[] getParameterValues(String name)
- Description
- Returns all the values of the named parameter as an array of String objects, or null if the parameter does not exist. A single value is returned in an array of length 1.
public abstract String getProtocol()
- Description
- Returns the name and version of the protocol used by the request as a string of the form protocol/major-version.minor-version. Equivalent to the CGI variable SERVER_PROTOCOL.
public abstract BufferedReader getReader() throws IOException
- Description
- This method retrieves the input stream as a BufferedReader object, which should be used for reading character-based input, since the reader translates charsets as appropriate. This method throws an IllegalStateException if getInputStream() has been called before on this same request. It throws an UnsupportedEncodingException if the character encoding of the input is unsupported or unknown. This method was introduced in the Servlet API 2.0.
public abstract String getRealPath(String path)
- Description
- Returns the real file system path of any given "virtual path" or null if the translation cannot be performed. If the given path is "/" it returns the document root for the server. If the given path is the same as the one returned by getPathInfo(), it returns the same real path as would be returned by getPathTranslated(). There is no CGI counterpart.
public abstract String getRemoteAddr()
- Description
- Returns the IP address of the client machine as a String. This information comes from the socket connecting the server to the client, so the remote address may be that of a proxy server. It is the same as the CGI variable REMOTE_ADDR.
public abstract String getRemoteHost()
- Description
- Returns the name of the client host. This comes from the socket connecting the server to the client and may be the name of a proxy server. It is the same as the CGI variable REMOTE_HOST.
public abstract String getScheme()
- Description
- This method returns the scheme used to make this request. Examples include "http", "https", and "ftp", as well as the newer Java-specific schemes "jdbc" and "rmi".
public abstract String getServerName()
- Description
- Returns the name of the server that received the request. It is an attribute of the ServletRequest because it can change for different requests if the server has more than one name (a situation that might arise if one server is hosting more than one web site). Equivalent to the CGI variable SERVER_NAME.
public abstract int getServerPort()
ServletResponse | ||
|
||
Servlets use ServletResponse objects to send MIME encoded data back to the client. The servlet engine creates this object and passes it to the servlet's service() method. To send binary data, use the ServletOutputStream returned by getOutputStream(). To send character data, use the PrintWriter returned by getWriter(). You can explicitly set the output's MIME type using the setContentType() method. If you elect to set this manually, do so before calling getWriter(), as getWriter() consults the content type to determine which charset to use. Consult RFC 2045 at http:/www.ietf.org/rfc/rfc2045.txt for more information on MIME.
public interface ServletResponse { // Methods public abstract String getCharacterEncoding(); // New in 2.0 public abstract ServletOutputStream getOutputStream() throws IOException; public abstract PrintWriter getWriter() throws IOException; // New in 2.0 public abstract void setContentLength(int len); public abstract void setContentType(String type); }
public abstract String getCharacterEncoding()
- Description
- Returns the charset encoding used for this MIME body. This is the charset specified by the assigned content type or "ISO-8859-1" if no charset has been specified. This method was introduced in the Servlet API 2.0.
public abstract ServletOutputStream getOutputStream() throws IOException
- Description
- Returns a ServletOutputStream for writing binary (byte-at-a-time) response data. No encoding is performed. Throws an IllegalStateException if getWriter() has already been called on this response.
public abstract PrintWriter getWriter() throws IOException
- Description
- Returns a PrintWriter for writing character-based response data. The writer encodes the characters according to whatever charset is given in the content type. If no charset is specified in the content type, as is generally the case, the writer uses the ISO-8859-1 (Latin-1) encoding appropriate for Western European languages. Throws an IllegalStateException if getOutputStream() has already been called on this response, and an UnsupportedEncodingException if the encoding of the output stream is unsupported or unknown. This method was introduced in the Servlet API 2.0.
public abstract void setContentLength(int len)
- Description
- Sets the length of the content being returned by the server. In HTTP servlets, it sets the HTTP Content-Length header. HTTP servlets use this method to enable persistent connections and help client progress monitors, so its use is optional.
public abstract void setContentType(String type)
SingleThreadModel | ||
|
||
SingleThreadModel is a tag interface with no methods. If a servlet implements this interface, the server ensures that each instance of the servlet handles only one service request at a time. Servers implement this functionality by maintaining a pool of servlet instances and dispatching incoming requests to free servlets within the pool. SingleThreadModel provides easy thread safety, but at the cost of increased resource requirements as more servlet instances are loaded at any given time.
public interface SingleThreadModel { }
UnavailableException | ||
|
||
A servlet can throw an UnavailableException at any time to indicate that it is not available to service client requests. There are two types of unavailability: permanent (where some corrective action must be taken on the server) and temporary. A servlet is temporarily unavailable if some system-wide problem momentarily prevents it from servicing requests. This may include network troubles or a crashed or overloaded database server. To mark a servlet as temporarily unavailable, specify a duration (in seconds) when constructing the exception. Well-written servers check back after this time. Servlet implementations are not required to treat temporary and permanent unavailability differently.
Servers generally provide clients with polite error messages when handling requests for unavailable servlets. For example, the Java Web Server returns a 404 (Unavailable) message.
public class UnavailableException extends ServletException { // Constructors public UnavailableException(int seconds, Servlet servlet, String msg); public UnavailableException(Servlet servlet, String msg); // Instance Methods public Servlet getServlet(); public int getUnavailableSeconds(); public boolean isPermanent(); }
public UnavailableException(int seconds, Servlet servlet, String msg) public UnavailableException(Servlet servlet, String msg)
- Description
- Constructs an UnavailableException with a given explanatory message. You can optionally specify a period of unavailability, given in seconds. If no time estimate can be made, a nonpositive value can be passed to the constructor, indicating permanent unavailability. Notice the nonstandard placement of the optional seconds parameter as the first parameter instead of the last. This may be changed in an upcoming release.
public Servlet getServlet()
- Description
- Returns the servlet that threw this exception.
public int getUnavailableSeconds()
- Description
- Returns the number of seconds for which this servlet will be unavailable. A negative number indicates permanent unavailability. No attempt is made to compensate for the time elapsed since the exception was thrown.
public boolean isPermanent()
Copyright © 2001 O'Reilly & Associates. All rights reserved.
This HTML Help has been published using the chm2web software. |