by Dinesh Thakur Category: introduction to Servlet

Before creating the first servlet, you need to understand the Servlet API and Tomcat Servlet container. The Servlet API provides interfaces and classes that are required to built servlets. These interfaces and classes are group into the following two packages :

• javax.servlet

• javax.servlet.http

One should remember that these packages are not part of Java core packages, instead they are standard extension provides by Tomcat. Therefore, they are not included with Java SE 6. First, we shall discuss in detail javax.servlet package, its classes and interfaces and then javax.servlet.http package.

javax.servlet PACKAGE

The javax.Servlet package contains a number of interfaces and classes that establish the framework in which servlets operate. The classes and interface in this package are protocol independent. The Fig. shows classes and interfaces in this package.

 Classes and Interfaces of javax.servlet PACKAGE

The javax. servlet package contains many interfaces and classes. Some of the interfaces and classes  are listed in table.





Declares life cycle methods that all servlets must implement.


Allows servlets to get initialization parameters


Allows servlets to communicate with its servlet container.


Provides client request information to a servlet.


Assist a servlet in sending a response to the client.





Provides a basic implementation of the Servlet interface for protocol independent servlets


Provides an input stream for reading binary data from a client request.


Provides an output stream for sending binary data to the client.


Defines a general exception, a servlet can throw when it encounters difficulty.


Indicates that a servlet is not available to service client request.


The Servlet interface defines the basic structure of a servlet. This interface specifies the contract between the servlet container and a servlet. In other words, it is the interface that container use to reference servlets. All servlets implement this interface, either directly or indirectly by extending either the GenericServlet or HttpServlet class which implements the Servlet interface. This interface defines methods that provide basic servlet functionality - to initialize a servlet, to receive and respond to client requests and to destroy a servlet and its resources. These methods are invoked by the servlet container. The Servlet interface defines the following methods:

void init (ServletConfig config) throws ServletException: It is called to initialize the servlet. This method is called only once automatically by the servlet container when it loads the servlet. This method can be used to perform one-time activities such as creating database connections, read initialization parameters etc. The container pass an object of type ServletConfig which can be used to obtain initialization parameters.

ServletConfig getServletConfig () : It returns the ServletConfig object passed to the servlet during init () method.

String getServletlnfo () : It returns a String object containing information about the servlet such as author, creation date, version and copyright etc.

void service(ServletRequest request, ServletResponse response) throws ServletException, IOException : This is the entry point for executing application logic in a servlet. It is called by the servlet container to process a request from a client. A servlet receives request information via the ServletRequest object and sends the data back to the client via ServletResponse object.

void destroy () : This method is called by the servlet container before removing a servlet out of service. This may occur if the web server is being shutdown or the servlet container needs to free some memory. Resources used by the servlet such as open database connections, open files should be deallocated here.

ServletConfig INTERFACE

The ServletConfig interface is implemented by the server. Servers use ServletConfig object to pass configuration information to servlets. The configuration information contains initialization parameters, the name of the servlet and a ServletContext object which gives servlet information about the container. The methods declared in this interface are



String getlnitParameter

(String name)

It returns a String containing the value of a named initialization parameter or null if specified parameter does not exist.

String getServletName()

It returns the name assigned to a servlet in its deployment descriptor.

If no name is specified, this returns the servlet class name instead.



It returns a reference to the ServletContext object for the associated servlet, allowing interaction with the server.



It returns the name of the servlet's initialization parameters as an enumeration of String objects or an empty Enumeration if no initialization parameters are specified.

ServletContext INTERFACE

The ServletContext interface provides a means for servlets to communicate with its servlet container. This communication includes finding path information, accessing other servlets running on the server, writing to the server log, getting MIME type of a file and so on. There is one context per web application per Java Virtual Machine.

The ServletContext object is a container within the ServletConfig object which the web server provides to the servlet when the servlet is initialized ..

The ServletContext interface specifies the following methods:



Object setAttribute(String name)

It sets the servlet container attribute with the given name or null if the attribute doesnot exist.

String getMimeType(String fileName)

It returns the MIME type of a specified file or null if it is not known.

String getRealPath(String vpath)

It returns the real path (on the server file system) that corresponds to the virtual path vpath.

String getServerlnfo()

It returns the name and version of the servlet container separated by a forward slash (f).

void setAttribute(String

name, Object obj)

It binds a specified object to a given attribute name in this servlet context.

void log (String msg)

It writes the specified message to a servlet log file usually an

event log.

void log(String msg, Throwable t)

It writes the specified message msg and a stack trace for a specified Throwable exception t to the servlet log file.

ServletRequest INTERFACE

The ServletRequest interface defines an object that encapsulates information about a single client request. The servlet container creates a ServletRequest object and passes it as an argument to the servlet's service () method. Data provided by the object generally includes parameter names and values, implementation specific attributes and an input stream for reading binary data from the request body. Some of the methods specified in it are given below :



Object getAttribute(String name)

It returns the value of the named attribute as an object, or null if the named attribute does not exist.

Enumeration getAttributeNames()

It returns an enumeration of all attributes contained in the request.

int getContentLength()

It returns the length (in bytes) of the content being sent via the

input stream or -1 if the length is not known.

String getContentType()

It request the MIME type of the body of the request or null if the type is not known.

ServletlnputStream getlnputStream()

It retrieves the body of the request as binary data using

Servletlnputstream object.

String getparameter (String name)

It returns the value of the specified parameter or null if the

parameter does not exists or without a value.

Enumeration getParameterNames()

It returns all the parameter names as enumeration of String


String [] getParameterValues(String name)

It returns an array of String objects containing all the values of the specified parameter or null if the parameter does not exist.

String getprotocol()

It returns the name and version of the protocol used by the request.

String getParameterAddr()

It returns the IP address of the client that sent the request.

String getRemoteHost()

It returns the name of the client that send the request.

String getScheme()

It returns the name and the scheme used to make the request.

For example : http, ftp,https etc.

String getServerName()

It returns the name of the server that receives the request.

int getServerport()

It returns the port number on which the request was received.

BufferedReader getReader()

It retrieves the body of the request as character data.

ServletResponse INTERFACE

The ServIetResponse interface is the response counterpart of the ServIetRequest object. It defines an object to assist a servlet in sending MIME encoded data back to the client. Theservlet container create a ServIetResponse object and passes it as an argument to the servlet's service () method.

Some of the most commonly used methods of this interface are as follows:



void setContentType(String type)

It sets the MIME type of the response being sent to the client. For example, in case of HTML, the MIME type should be set to "text/HTML".

void setContentLength(int Ien)

It sets the length of the content being returned by the server. In HTTP servlets, this method sets the HTTP content -length header.

ServIetOutputStream getOutputStream()

It returns a ServIetOutStream object than can be used for writing binary data into the response.

printWriter getWriter()

It returns a PrintWriter object that can send character text in the response.

String getCharacterEncoding()

It returns the name of the charset used for the MIME body sent in the response.

SingleThreadModel INTERFACE

SingIeThreadModel is a special marker interface with no methods. If a servlet implement this interface, the servlet container ensures that the servlet handles only one request at a time. If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service () method.

Servlet container implements this functionality by maintaining a pool of servlet instances. For each incoming request, the container allocates a servlet instance from the pool and once the service is completed, the container returns the instance to the pool. This interface provides easy thread safety but at the cost of increased resource requirements as more servlet instances are loaded at any given time.

GenericServlet CLASS

The GenericServlet class provides a basic implementation of the Servlet interface. This is an abstract class and all subclasses should implement the service () method. This class implements both Servlet as well as ServletConfig interface. It has the following methods in addition to those declared in Servlet and ServletConfig interfaces.



void init ()

It is similar to init (ServletConfig config). This method is provided as a convenience so that servlet developers do not have to worry about storing the ServletConfig object.

void log (String msg)

It writes the specified message msg to a servlet log file.

void log(String msg, Thowable t)

It writes the name of the servlet, the specified message msg and the stack trace t to the servlet log file.

ServletInputStream CLASS

The ServletlnputStream class extends InputStream. It provides input stream for reading binary data from a client request. A servlet obtains a ServletlnputStream object from the getlnputStream () method of ServletRequest. It defines the default constructor which does nothing. In addition, it also contains the following method:

• int readLine (byte [] buf, int off, int len) : This method reads bytes from the input stream into the byte array buf, starting at the specified offset off. It stops reading when it encounters an '\n' or it has read len number of bytes. The method returns the actual number of bytes read or -1 if an end of the stream is reached.

ServletOutputStream CLASS

The ServletOutputStream class extends OutputStream. It provides an output stream for sending binary data back to the client. A servlet obtains a ServletOutputStream object from the getOutputStream () method of ServletResponse. It also has a default constructor that does nothing. In addition, it also includes a range of print () and println () methods for sending text or HTML. It takes the following form

• void print(type v)

• void println(type v)

Here, type specifies the datatype int, char, float, long, String, double, boolean and v specifies the data to be written.

ServletException CLASSES

The javax.Servlet defines two exception classes ServletException and UnavailableException. The ServletException is a generic exception which can be thrown by servlets encountering difficulties. UnavailableException is a special type of servlet exception which extends the ServletException class. The purpose of this class is to indicate to the servlet container that the servlet is either temporarily or permanently unavailable to service client requests.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.