Thursday 30 March 2017

The javax.servlet Package - Java Tutorials

The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate. The following table summarizes the core interfaces that are provided in this package. The most significant of these is Servlet. All servlets must implement this interface or extend a class that implements the interface. The ServletRequest and ServletResponse interfaces are also very important.


Interface  --  Description

Servlet:  Declares life cycle methods for a servlet.

ServletConfig:  Allows servlets to get initialization parameters.

ServletContext:  Enables servlets to log events and access information about their environment.

ServletRequest:  Used to read data from a client request.

ServletResponse:  Used to write data to a client response.

SingleThreadModel:  Indicates that the servlet is thread safe.

The following table summarizes the core classes that are provided in the javax.servlet package.


Class  --  Description

GenericServlet:  Implements the Servlet and ServletConfig interfaces.

ServletInputStream:  Provides an input stream for reading requests from a client.

ServletOutputStream:  Provides an output stream for writing responses to a client.

ServletException:  Indicates a servlet error occurred.

UnavailableException:  Indicates a servlet is unavailable.

Let us examine these interfaces and classes in more detail.


The Servlet Interface

All servlets must implement the Servlet interface. It declares the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet. A method is also provided that allows a servlet to obtain any initialization parameters.


The Methods Defined by Servlet

void destroy( ):  Called when the servlet is unloaded.

ServletConfig getServletConfig( ):  Returns a ServletConfig object that contains any initialization parameters.

String getServletInfo( ):  Returns a string describing the servlet.

void init(ServletConfig sc) throws ServletException:  Called when the servlet is initialized. Initialization parameters for the servlet can be obtained from sc. An UnavailableException should be thrown if the servlet cannot be initialized.

void service(ServletRequest req, ServletResponse res) throws ServletException, IOException:  Called to process a request from a client. The request from the client can be read from req. The response to the client can be written to res. An exception is generated if a servlet or IO problem occurs.

The init( ), service( ), and destroy( ) methods are the life cycle methods of the servlet. These are invoked by the server. The getServletConfig( ) method is called by the servlet to obtain initialization parameters. A servlet developer overrides the getServletInfo( ) method to provide a string with useful information (for example, author, version, date, copyright). This method is also invoked by the server.


The ServletConfig Interface

The ServletConfig interface is implemented by the server. It allows a servlet to obtain configuration data when it is loaded. The methods declared by this interface are summarized here:

Method  --  Description

ServletContext getServletContext( ):  Returns the context for this servlet.

String getInitParameter(String param):  Returns the value of the initialization parameter named param.

Enumeration getInitParameterNames( ):  Returns an enumeration of all initialization parameter names.

String getServletName( ):  Returns the name of the invoking servlet.


The ServletContext Interface
The ServletContext interface is implemented by the server. It enables servlets to obtain information about their environment. 

The ServletRequest Interface
The ServletRequest interface is implemented by the server. It enables a servlet to obtain information about a client request. 

The ServletResponse Interface
The ServletResponse interface is implemented by the server. It enables a servlet to formulate a response for a client. 

The SingleThreadModel Interface
This interface is used to indicate that only a single thread will execute the service( ) method of a servlet at a given time. It defines no constants and declares no methods. If a servlet implements this interface, the server has two options. First, it can create several instances of the servlet. When a client request arrives, it is sent to an available instance of the servlet. Second, it can synchronize access to the servlet.


Various Methods Defined by ServletContext

Object getAttribute(String attr):  Returns the value of the server attribute named attr.

String getMimeType(String file):  Returns the MIME type of file.

String getRealPath(String vpath):  Returns the real path that corresponds to the virtual path vpath.

String getServerInfo( ):  Returns information about the server.

void log(String s):  Writes s to the servlet log.

void log(String s, Throwable e):  Write s and the stack trace for e to the servlet log.

void setAttribute(String attr, Object val):  Sets the attribute specified by attr to the value passed in val.


Various Methods Defined by ServletRequest

Object getAttribute(String attr):  Returns the value of the attribute named attr.

String getCharacterEncoding( ):  Returns the character encoding of the request.

int getContentLength( ):  Returns the size of the request. The value –1 is returned if the size is unavailable.

String getContentType( ):  Returns the type of the request. A null value is returned if the type cannot be determined.

ServletInputStream getInputStream( ) throws IOException:  Returns a ServletInputStream that can be used to read binary data from the request. An IllegalStateException is thrown if getReader( ) has already been invoked for this request.

String getParameter(String pname):  Returns the value of the parameter named pname.

Enumeration getParameterNames( ):  Returns an enumeration of the parameter names for this request.

String[ ] getParameterValues(String name ):  Returns an array containing values associated with the parameter specified by name.

String getProtocol( ):  Returns a description of the protocol.

BufferedReader getReader( ) throws IOException:  Returns a buffered reader that can be used to read text from the request. An IllegalStateException is thrown if getInputStream( ) has already been invoked for this request.

String getRemoteAddr( ):  Returns the string equivalent of the client IP address.

String getRemoteHost( ):  Returns the string equivalent of the client host name.

String getScheme( ):  Returns the transmission scheme of the URL used for the request (for example, “http”, “ftp”).

String getServerName( ):  Returns the name of the server.

int getServerPort( ):  Returns the port number.


Various Methods Defined by ServletResponse

String getCharacterEncoding( ):  Returns the character encoding for the response.

ServletOutputStream getOutputStream( ) throws IOException:  Returns a ServletOutputStream that can be used to write binary data to the response. An IllegalStateException is thrown if getWriter( ) has already been invoked for this request.

PrintWriter getWriter( ) throws IOException:  Returns a PrintWriter that can be used to write character data to the response. An IllegalStateException is thrown if getOutputStream( ) has already been invoked for this request.

void setContentLength(int size):  Sets the content length for the response to size.

void setContentType(String type):  Sets the content type for the response to type.


The GenericServlet Class
The GenericServlet class provides implementations of the basic life cycle methods for a servlet and is typically subclassed by servlet developers. GenericServlet implements the Servlet and ServletConfig interfaces. In addition, a method to append a string to the server log file is available. The signatures of this method are shown here:

      void log(String s)
      void log(String s, Throwable e)

Here, s is the string to be appended to the log, and e is an exception that occurred.

The ServletInputStream Class
The ServletInputStream class extends InputStream. It is implemented by the server and provides an input stream that a servlet developer can use to read the data from a client request. It defines the default constructor. In addition, a method is provided to read bytes from the stream. Its signature is shown here:

      int readLine(byte[ ] buffer, int offset, int size) throws IOException

Here, buffer is the array into which size bytes are placed starting at offset. The method
returns the actual number of bytes read or –1 if an end-of-stream condition is encountered.

The ServletOutputStream Class
The ServletOutputStream class extends OutputStream. It is implemented by the server and provides an output stream that a servlet developer can use to write data to a client response. A default constructor is defined. It also defines the print( ) and println( ) methods, which output data to the stream.

The Servlet Exception Classes
javax.servlet defines two exceptions. The first is ServletException, which indicates that a servlet problem has occurred. The second is UnavailableException, which extends ServletException. It indicates that a servlet is unavailable.

No comments:

Post a Comment