You are on page 1of 30


Introduction to Servlet
Servlets are modules that run inside request/response-oriented servers,
such as Java-enabled web servers, and extend them in some manner. For
example, a servlet might be responsible for taking data in an HTML order-entry
form and applying the business logic used to update a company's order
Servlets are to servers what applets are to browsers.
The Servlet API, which you use to write servlets, assumes nothing about
how a servlet is loaded, the server environment in which the servlet runs, or the
protocol used to transmit data to and from the user. This allows servlets to be
embedded in many different web servers.
Servlets are an effective substitute for CGI scripts: they provide a way to
generate dynamic documents that is both easier to write and faster to run. They
also address the problem of doing server-side programming with platformspecific APIs. Servlets are developed with the Java Servlet API, a standard Java
Example Uses
A few of the many applications for servlets include,
Processing data Posted over HTTPS using an HTML form, including
purchase order or credit card data. A servlet like this could be part of an
order-entry and processing system, working with product and inventory
databases, and perhaps an on-line payment system.
Allowing collaboration between people. A servlet can handle multiple
requests concurrently; they can synchronize requests to support systems
such as on-line conferencing.
Forwarding requests. Servlets can forward requests to other servers and
servlets. This allows them to be used to balance load among several
servers that mirror the same content. It also allows them to be used to
partition a single logical service over several servers, according to task
type or organizational boundaries.
Being a community of active agents. A servlet writer could define active
agents that share work among each other. Each agent would be a servlet,
and the agents could pass data among themselves.
Servlets are modules of Java code that run in a server application
Servlets are not restricted to but most commonly used with HTTP
Servlets use extension classes in

(the basic Servlet framework)

javax.servlet.http (extensions for HTTP requests)

Servlets vs CGI
A Servlet does not run in a separate process
A Servlet stays in memory between requests
There is only a single instance which answers all requests concurrently. This
saves memory and allows a Servlet to manage persistent data
CGI requires more memory & CPU time. Every link to every CGI program
causes web server to create a separate process in which to run CGI.

Servlet vs Applet:
An applet is a Java plug-in for web browser. Whereas servlet is a Java plug-in
for web server.
An applet extends the capabilities of web browser. Servlets are the Java
components that extends the capabilities of web server.
Applets adds functionality to web pages, but it has problems of compatibility &
bandwidth issues. Applets are programs embedded directly into web pages with
a web page; byte-code of an applet is downloaded to client box & executed by
browser. For big size applets the download time is very high. To run an Applet,
you must have compatible browser, but servlet code is being executed on server
side & no issues with browsers compatibility or long download times.
Servlets Can Do:
1. Dynamically build & return an HTML file based on client request.
2. Process user input passed by HTML form & return proper response.
3. Provide user authentication & other security mechanisms.
4. Interacts with server resources like database, other applications & network
5. Process input from many clients
6. Automatically attach web page design elements like headers / footers to all
pages returned by server.
7. Forward requests from one server to another & communicates with other
server resources.

8. Opens a new connection from server to applet on browser & keep

connection open allowing many data transfers on single connection.
Servlets are:
1. Portable Write once, run anywhere.
2. Persistent Can maintain states between requests. After loading it stays
resident in memory while serving incoming requests.
3. Extensible You can use object-oriented programs to reduce development
time. Servlets can be run on any servlet enabled web server.
4. Efficient Servlets initialization code is executed only 1 st time server loads it.
After this it will just call service method to handle request.
5. Powerful & Robust- Servlets can access entire JDK with class library that
includes network support, file support, database access.
6. Versatile Rich application program interface like relational database,
distributed objects(RMI), Enterprise Java Beans etc.
All servlets implements Servlet interface directly or by extending a class that
implements it such as GenericServlet or HttpServlet.
HttpServlet class is extended from GenericServlet.
Servlets donot have main () method, so it must implement javax.servlet.Servlet
- Has to implement service() method. This is an abstract method with formpublic abstract void service (ServletRequest req, ServletResponse res)
throws ServletException, IOException




Two objects that are received by service() method:

ServletRequest : Holds information that is being sent to servlet.
ServletResponse : To place the data you want to send back to servlet.

After extending this class it is not necessary to implement service()
method, as this class has by default implements it. The form is:
protected void service (HttpServletRequest req, HtppServletResponse res)
throws ServletException, IOException
This class has following methods, requires same parameters listed in service ()



service ()


To run or use servlets use Java Servlet Development Kit (JSDK)


JSDK is a package freely available from JavaSoft that includes all tools
needs to begin servlets.
It includes packages like javax.servlet & javax.servlet.http etc. that
contains all classes related to servlets.
It has simple test web server useful for testing servlet operations.
Directory Structure:
- Contains test servlet runner
- Contains class & interface documentation that
apidoc can be viewed with any web browser
examples lib
- contains /lib/jsdk.jar file, which compiler uses to
compile servlet API.
- Contains source code for servlet API.

Servlet Lifecycle
Servers load and run servlets, which then accept zero or more requests
from clients and return data to them. They can also remove servlets. These are
the steps of a servlets lifecycle.
a. init() - When a server loads a servlet, it runs the servlet's init method. The
server calls the init method once, when it loads the servlet, and will not call
it again unless it is reloading the servlet. The server can not reload a
servlet until after it has removed the servlet by calling the destroy method.
Initialization is allowed to complete before client requests are handled (that
is, before the service method is called) or the servlet is destroyed.
The form of init() is :
public void init (ServletConfig config) throws ServletException
b. service() - After the server loads and initializes the servlet, the servlet is
able to handle client requests. It processes them in its service method.
Each client's request has its call to the service method run in its own
servlet thread: the method receives the client's request, and sends the
client its response.
Servlets can run multiple service methods at a time. It is important,
therefore, that service methods be written in a thread-safe manner. For
example, if a service method might update a field in the servlet object, that
access should be synchronized. If, for some reason, a server should not
run multiple service methods concurrently, the servlet should implement
the SingleThreadModel interface. This interface guarantees that no two
threads will execute the servlet's service methods concurrently.
The form of service () is :
public void service (ServletRequest req, ServletResponse res) throws
ServletException, IOException
c. destroy() - Servlets run until they are removed from the service, for example,
at the request of a system administrator. When a server removes a servlet,
it runs the servlet's destroy method. The method is run once; the server
will not run it again until after it reloads and reinitializes the servlet. When
the destroy method runs, however, other threads might be running service
requests. If, in cleaning up, it is necessary to access shared resources
(such as network connections to be closed), that access should be
The form of destroy () is :
public void destroy ()

Servlet Life Cycle:

Server Loads Servlets

Server creates one or more

instances of servlet class

Server calls init() method of each

servlet instance

Server calls init () method of each

servlet instance

Servlet request is received

Servlet instance selected & called

service () method

Process service() request & return

output to client.
Servlet waits until next request is
received or unloaded by server.
Server unloads the servlet after
calling destroy() method.

Servlet Architecture Overview

The central abstraction in the Servlet API is the Servlet interface. All
servlets implement this interface, either directly or, more commonly, by extending
a class that implements it such as HttpServlet. The Servlet interface provides for
methods that manage the servlet and its communications with clients.
When a servlet accepts a call from a client, it receives two objects: one is a
ServletRequest and the other is a ServletResponse.
ServletRequest class: Encapsulates the communication from the client to the
server. The ServletRequest interface allows the servlet access to information
such as
1. The names of the parameters passed in by the client
2. The protocol (scheme) being used by the client
3. The names of the remote host that made the request and the server
that received it.
4. It also provides the servlet with access to the input stream,
ServletInputStream, through which the servlet gets data from clients
that are using application protocols such as the HTTP POST and PUT
Subclasses of ServletRequest allow the servlet to retrieve more protocol-specific
data. For example, HttpServletRequest contains methods for accessing HTTPspecific header information.
ServletResponse class: Encapsulates the communication from the servlet back
to the client. The ServletResponse interface gives the servlet
1. Methods for replying to the client.
2. It allows the servlet to set the content length and mime type of the reply
3. Provides an output stream, ServletOutputStream, and a Writer
through which the servlet can send the reply data.
Subclasses of ServletResponse give the servlet more protocol-specific
capabilities. For example, HttpServletResponse contains methods that allow
the servlet to manipulate HTTP-specific header information.
Writing the Servlet
Servlets implement the javax.servlet.Servlet interface. While servlet
writers can develop servlets by implementing the interface directly, this is usually
not required. Because most servlets extend web servers that use the HTTP
protocol to interact with clients, the most common way to develop servlets is by
specializing the javax.servlet.http.HttpServlet class.
The HttpServlet class implements the Servlet interface by extending the
GenericServlet base class, and provides a framework for handling the HTTP
protocol. Its service method supports standard HTTP/1.1 requests by dispatching
each request to a method designed to handle it.

By default, servlets written by specializing the HttpServlet class can have

multiple threads concurrently running its service method. If, for whatever reason,
you would like to have only a single thread running a service method at a time,
then in addition to extending the HttpServlet, your servlet should also implement
the SingleThreadModel interface.
For example,
public class SurveyServlet extends HttpServlet
implements SingleThreadModel {
/* typical servlet code, with no threading concerns in the service method.
No extra code for the SingleThreadModel interface. */
... }
The javax.servlet Package
The javax.servlet package defines the following six interfaces and three classes:
javax.servlet interfaces

Servlet--The Servlet interface must be implemented by all servlets. The

init() and destroy() methods are invoked by the server to start and stop a
servlet. The getServletConfig() and getServletInfo() methods are overridden to return information about a servlet. The service() method is
invoked by the server so that a servlet can perform its service. It has two
parameters--one of the ServletRequest interface and one of the
ServletResponse interface.

ServletRequest--The ServletRequest interface encapsulates a client

request for service. It defines a number of methods for obtaining
information about the server, requester, and request.
Methods of ServletRequest interface:

1. public abstract int getContentLength()- Returns an integer representation

of the total length of the requests data portion or 1 if unknown.
Common MIME(Multipurpose Internet Mail Extensions) are:
text/plain, text/html, image/gif, image/jpg
2. public abstract String getContentType() Returns MIME media type of
requests data or null if request contains only header (no data)
3. public abstract ServletInputStream getInputStream () throws IOException
Returns an inputstream in the form of a ServletInputStream object.
4. public abstract String getParameter(String)- Returns value of specified
parameter or null if parameter does not exist.
5. public abstract String[ ] getParameterValues(String)- to return a string
array containing all values of a specified parameter.

6. public abstract Enumeration getParamterNames()- Returns name of

each name/value pair passed in the request.
7. public abstract String getProtocol()- Returns a string describing protocol
used by servlet.
8. public abstract BufferedReader getReader() throws IOException
Returns a BufferedReader for reading text from data portion of request.
9. public abstract String getRemoteAddr()- Returns an IP address of client
that sent the request.
10. public abstract String getRemoteHost()- Returns clients fully qualified
host name.
11. public abstract String getScheme()- Returns scheme used by request.
Ex.- http, https, ftp, telnet.
12. public abstract String getServerName()- Returns hostname of server on
which servlet running.
13. public abstract int getServerPort()- Returns an integer representing port
on which the clients request was received.


ServletResponse--The ServletResponse interface is used by a servlet to

respond to a request by sending information back to the requester.
Methods of ServletResponse interface:
public abstract ServletOutputStream getOutputStream() throws
IOException- Returns an output stream over which binary data can be
transmitted back to client.
public abstract PrintWriter getWriter() throws IOException- Returns a
PrintWriter object for purpose of returning text information to the client.
public abstract void setContentLength(int len) - sets value of contentlength HTTP header in response.
public abstract void setContentType(String type)- sets content-type
HTTP header in response.
ServletConfig--The ServletConfig interface is used by the server to pass
configuration information to a servlet. Its methods are used by the servlet
to retrieve this information.
ServletContext--The ServletContext interface defines the environment in
which an applet is executed. It provides methods that are used by applets
to access environment information.
SingleThreadModel--The SingleThreadModel interface is used to identify
servlets that must be thread-safe. If a servlet implements this interface, the
Web server will not concurrently execute the service () method of more
than one instance of the servlet.

javax.servlet classes

GenericServlet--The GenericServlet class is a convenience class that

implements the Servlet interface. You can subclass this class to define
your own servlets.

ServletInputStream--The ServletInputStream class is used to access

request information supplied by a Web client. An object of this class is
returned by the getInputStream() method of the ServletRequest interface.
ServletOutputStream--The ServletOutputStream class is used to send
response information to a Web client. An object of this class is returned by
the getOutputStream() method of the ServletResponse interface.

The javax.servlet.http Package

The javax.servlet.http package is used to define HTTP-specific servlets. It
defines the following interfaces and classes.
javax.servlet.http interfaces

HttpServletRequest--The HttpServletRequest interface extends the

ServletRequest interface and adds methods for accessing the details of an
HTTP request.

1. public abstract String getAuthType()- returns a string describing the
authentication scheme employed by client.
2. public abstract Cookie[ ] getCookies() Returns cookies from request in
form of an array of cookie objects.
3. public abstract String getMethod() Returns HTTP method i.e get, post,
put used by request.
4. public abstract String getPathInfo()- Returns any path information
following server path but prior to query string.
5. public abstract String getQueryString() Returns query string of a URL.
6. public abstract String getServletPath()- Returns path to servlet being
invoked. Ex. http://localhost:8080/servlet/GetPathServlet/html/public
op- /servlet/GetPathServlet
7. public abstract String getRemoteUser()- Returns name of user making
8. public abstract int getRequestedSessionId()- Returns session id
contained in request.
9. public abstract String getRequestURL()- Returns part of requested URL
left of QueryString.

HttpServletResponse--The HttpServletResponse interface extends

the ServletResponse interface and adds constants and methods for
returning HTTP-specific responses.
1. public abstract void addCookie (Cookie c)- adds a cookie to HTTP
response. Cookie object resides in javax.servlet.http package. Are
transmitted within HTTP header, useful for managing state on web &
setting user preferences.

2. public abstract boolean containsHeader (String)- Determines whether a

specified header is contained in response. If the header field exists in
response message, then true is returned.
3. public abstract void sendError (int statuscode) throws IOException
public abstract void sendError (int statuscode, String s) throws
IOExcpetion- Returns an error message to client according to specified
status code.
4. public abstract void sendRedirect (String location) throws
IOException- sends a temporary redirect message to client according to
specified location. Location parameter must be an absolute URL. Relative
URLs are not permitted.
Ex. res.sendRedirect (
5. public abstract void setDateHeader (String s, long date)- adds a new
header to the response. Name parameter sets the header name & date
parameter sets the date. Date is specified using number of milliseconds
since midnight Jan. 01 1970 GMT.
6. public abstract void setHeader (String name, String val)
7. public abstract void setIntHeader (String s, int val)
8. public abstract void setStatus (int statuscode)
public abstract void setStatus (int sc, String s)
The integer constants/status codes are all public static final int
Status code (202) indicating that a request was accepted for processing,
but was not completed.
Status code (400) indicating the request sent by the client was syntactically
Status code (100) indicating the client can continue.
Status code (504) indicating that the server did not receive a timely
response from the upstream server while acting as a gateway or proxy.
Status code (410) indicating that the resource is no longer available at the
server and no forwarding address is known.
Status code (505) indicating that the server does not support or refuses to
support the HTTP protocol version that was used in the request message.
Status code (500) indicating an error inside the HTTP server which
prevented it from fulfilling the request.
Status code (405) indicating that the method specified in the Request-Line
is not allowed for the resource identified by the Request-URI.

Status code (301) indicating that the resource has permanently moved to a
new location, and that future references should use a new URI with their
Status code (302) indicating that the resource has temporarily moved to
another location, but that future references should still use the original URI
to access the resource.
Status code (406) indicating that the resource identified by the request is
only capable of generating response entities which have content
characteristics not acceptable according to the accept headerssent in the
Status code (404) indicating that the requested resource is not available.
Status code (200) indicating the request succeeded normally.
Status code (408) indicating that the client did not produce a requestwithin
the time that the server was prepared to wait.
Status code (503) indicating that the HTTP server is temporarily
overloaded, and unable to handle the request.
HttpSession--This interface is implemented by servlets to enable them to
support browser-server sessions that span multiple HTTP requestresponse pairs. Since HTTP is a stateless protocol, session state is
maintained externally using client-side cookies or URL rewriting. This
interface provides methods for reading and writing state values and
managing sessions.
HttpSession defines methods, which store these types of data:

Standard session properties, such as an identifier for the session, and the
context for the session.
Application layer data, accessed using this interface and stored using a
dictionary-like interface.

The following code snippet illustrates getting and setting the session data value.
//Get the session object - "request" represents the HTTP servlet request
HttpSession session = request.getSession(true);
//Get the session data value - an Integer object is read from
//the session, incremented, then written back to the session.
//sessiontest.counter identifies values in the session
Integer ival = (Integer) session.getValue("sessiontest.counter");
if (ival==null)
ival = new Integer(1);
ival = new Integer(ival.intValue() + 1);

session.putValue("sessiontest.counter", ival);
An implementation of HttpSession represents the server's view of the session.
The server considers a session to be new until it has been joined by the client.
Until the client joins the session, the isNew method returns true. A value of true
can indicate one of these three cases:

the client does not yet know about the session

the session has not yet begun
the client chooses not to join the session. This case will occur if the client
supports only cookies and chooses to reject any cookies sent by the
server. If the server supports URL rewriting, this case will not commonly

It is the responsibility of developers to design their applications to account for

situations where a client has not joined a session. For example, in the following
code snippet isNew is called to determine whether a session is new. If it is, the
server will require the client to start a session by directing the client to a welcome
page welcomeURL where a user might be required to enter some information
and send it to the server before gaining access to subsequent pages.
//Get the session object - "request" represents the HTTP servlet request
HttpSession session = request.getSession(true);
//insist that the client starts a session
//before access to data is allowed
//"response" represents the HTTP servlet response
if (session.isNew()) {
response.sendRedirect (welcomeURL);
1. public abstract String getId() - Returns the identifier assigned to this session.
An HttpSession's identifier is a unique string that is created and maintained by
2. public abstract HttpSessionContext getSessionContext()
Returns the context in which this session is bound.
3. public abstract long getCreationTime()
Returns the time at which this session representation was created, in
milliseconds since midnight, January 1, 1970 UTC.
4. public abstract long getLastAccessedTime()
Returns the last time the client sent a request carrying the identifier
assigned to the session. Time is expressed as milliseconds since midnight,

January 1, 1970 UTC. Application level operations, such as getting or setting a

value associated with the session, does not affect the access time.
This information is particularly useful in session management policies. For
a session manager could leave all sessions which have not been
used in a long time in a given context.
the sessions can be sorted according to age to optimize some task.
Returns: The last time the client sent a request carrying the identifier assigned
to the session
5. public abstract void invalidate()
Causes this representation of the session to be invalidated and removed
from its context.
6. public abstract void putValue(String name, Object value)
Binds the specified object into the session's application layer data with the
given name. Any existing binding with the same name is replaced. New (or
existing) values that implement the HttpSessionBindingListener interface will call
its valueBound() method.
name - the name to which the data object will be bound. This parameter cannot
be null.
value - the data object to be bound. This parameter cannot be null.
7. public abstract Object getValue(String name)
Returns the object bound to the given name in the session's application
layer data. Returns null if there is no such binding.
Parameters: name - the name of the binding to find
Returns: the value bound to that name, or null if the binding does not exist.
8. public abstract void removeValue(String name)
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. The value
that implements the HttpSessionBindingListener interface will call its
valueUnbound() method.
Parameters: name - the name of the object to remove
9. public abstract String[] getValueNames()
Returns an array of the names of all the application layer data objects
bound into the session. For example, if you want to delete all of the data objects
bound into the session, use this method to obtain their names.
Returns: an array containing the names of all of the application layer data
objects bound into the session
10. 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. For example, if the
server supported only cookie-based sessions and the client had completely
disabled the use of cookies, then calls to HttpServletRequest.getSession() would
always return "new" sessions.
Returns: true if the session has been created by the server but the client has
not yet acknowledged joining the session; false otherwise
All of these methods throws IllegalStateException - if an attempt is made to
access session data after the session has been invalidated.
HttpSessionBindingListener--This event listening interface is implemented by classes whose objects are associated with HTTP sessions. The
valueBound () method is used to notify an object that it is bound to an
HTTP session, and the valueUnbound () method is used to notify an object
that it is unbound from an HTTP session.

HttpSessionContext--This interface is used to represent a collection of

HttpSession objects that are associated with session IDs. The getIds()
method returns a list of session IDs. The getSession() method returns the
HttpSession object associated with a particular session ID. Session IDs
are implemented as String objects.

1. public abstract HttpSession getSession (String sessionId)
Returns the session bound to the specified session ID.
Parameters: sessionID - the ID of a particular session object
Returns: The session name. Returns null if the session ID does not refer to a
valid session.
2. public abstract Enumeration getIds()
Returns an enumeration of all of the session IDs in this context.
Returns: an enumeration of all session IDs in this context
javax.servlet.http classes
Cookie--This class represents an HTTP cookie. Cookies are used to maintain
session state over multiple HTTP requests. They are named data values that are
created on the Web server and stored on individual browser clients. The Cookie
class provides the method for getting and setting cookie values and attributes.
public class Cookie
extends Object
implements Cloneable

This class represents a "Cookie", as used for session management with

HTTP and HTTPS protocols. Cookies are used to get user agents (web browsers
etc) to hold small amounts of state associated with a user's web browsing.
Common applications for cookies include storing user preferences,
automating low security user sign on facilities, and helping collect data used for
"shopping cart" style applications.
Cookies are named, and have a single value. They may have optional
attributes, including a comment presented to the user, path and domain qualifiers
for which hosts see the cookie, a maximum age, and a version. Current web
browsers often have bugs in how they treat those attributes, so interoperability
can be improved by not relying on them heavily.
Cookies are assigned by servers, using fields added to HTTP response
headers. In this API, cookies are saved one at a time into such HTTP response
headers, using the javax.servlet.http.HttpServletResponse.addCookie method.
User agents are expected to support twenty cookies per host, of at least four
kilobytes each; use of large numbers of cookies is discouraged.
Cookies are passed back to those servers using fields added to HTTP
request headers. In this API, HTTP request fields are retrieved using the cookie
module's javax.servlet.http.HttpServletRequest.getCookies method. This returns
all of the cookies found in the request. Several cookies with the same name can
be returned; they have different path attributes, but those attributes will not be
visible when using "old format" cookies.
Cookies affect the caching of the web pages used to set their values. At
this time, none of the sophisticated HTTP/1.1 cache control models are
supported by this class. Standard HTTP/1.0 caches will not cache pages which
contain cookies created by this class.
Constructorpublic Cookie (String name, String value)
Defines a cookie with an initial name/value pair.
name - name of the cookie
value - value of the cookie
1. public void setComment(String purpose)
If a user agent (web browser) presents this cookie to a user, the cookie's
purpose will be described using this comment. This is not supported by version
zero cookies.
2. public String getComment()
Returns the comment describing the purpose of this cookie, or null if no
such comment has been defined.
3. public void setDomain(String pattern)
This cookie should be presented only to hosts satisfying this domain name
pattern. Briefly, a domain name name begins with a dot ("") and
means that hosts in that DNS zone ("", but not "")

should see the cookie. By default, cookies are only returned to the host
which saved them.
4. public String getDomain()
Returns the domain of this cookie.
5. public void setMaxAge(int expiry)
Sets the maximum age of the cookie. The cookie will expire after that many
seconds have passed. Negative values indicate the default behaviour: the cookie
is not stored persistently, and will be deleted when the user agent (web browser)
exits. A zero value causes the cookie to be deleted.
6. public int getMaxAge()
Returns the maximum specified age of the cookie. If none was specified, a
negative value is returned, indicating the default behaviour described with
7. public void setPath(String uri)
This cookie should be presented only with requests beginning with this
URL. Basically, URLs in the same "directory" as the one which set the cookie,
and in subdirectories, can all see the cookie unless a different path is set.
8. public String getPath()
Returns the prefix of all URLs for which this cookie is targetted.
9. public void setSecure (boolean flag)
Indicates to the user agent that the cookie should only be sent using a
secure protocol (https). This should only be set when the cookie's originating
server used a secure protocol to set the cookie's value.
10. public boolean getSecure()
Returns the value of the 'secure' flag.
11. public String getName()
Returns the name of the cookie. This name may not be changed after the
cookie is created.
12. public void setValue(String newValue)
Sets the value of the cookie. BASE64 encoding is suggested for use with
binary values.
With version zero cookies, you need to be careful about the kinds of values
you use. Values with various special characters (whitespace, rackets and
parentheses, the equals sign, comma, double quote, slashes, question marks,
the "at" sign, colon, and semicolon) should be avoided. Empty values may not
behave the same way on all browsers.
13. public String getValue()
Returns the value of the cookie.
14. public int getVersion()
15. public void setVersion(int v)
Sets the version of the cookie protocol used when this cookie saves itself.
16. public Object clone()
Returns a copy of this object.
Overrides: clone in class Object

// Create a new Cookie
Cookie c=new Cookie(name,abcd);
// Set life of cookie, that expires in 2 days.
// Add cookie to clients machine.

// To display all cookies

Cookie[ ] c=req.getCookies();
for(int i=0;i<c.length;i++)
HttpServlet--The HttpServlet class extends the GenericServlet class to
use the HttpServletRequest and HttpServletResponse interfaces.

public abstract class HttpServlet

extends GenericServlet
implements Serializable
An abstract class that simplifies writing HTTP servlets. It extends the
GenericServlet base class and provides an framework for handling the HTTP
protocol. Because it is an abstract class, servlet writers must subclass it and
override at least one method. The methods normally overridden are:
Servlets typically run inside multi-threaded servers; servlets must be written to
handle multiple service requests simultaneously. It is the servlet writer's
responsibility to synchronize access to any shared resources. Such resources
include in-memory data such as instance or class variables of the servlet, as well
as external components such as files, database and network connections.
Constructorpublic HttpServlet()
The default constructor does nothing.
1. doGet
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
Performs the HTTP GET operation; the default implementation reports an
HTTP BAD_REQUEST error. Overriding this method to support the GET

operation also automatically supports the HEAD operation. (HEAD is a GET that
returns no body in the response; it just returns the request HEADer fields.)
The GET operation is expected to be safe: without any side effects for
which users might be held responsible. For example, most form queries have no
side effects. Requests intended to change stored data should use some other
HTTP method.
req - HttpServletRequest that encapsulates the request to the servlet
resp - HttpServletResponse that encapsulates the response from the servlet
Throws: IOException
if detected when handling the request
Throws: ServletException
if the request could not be handled
2. getLastModified
protected long getLastModified(HttpServletRequest req)
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
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
req - HttpServletRequest that encapsulates the request to the servlet
The time the requested entity was last modified, as the difference,
measured in milliseconds, between that time and midnight, January 1, 1970
UTC. Negative numbers indicate this time is unknown.
3. doPost
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
Performs the HTTP POST operation; the default implementation reports an
HTTP BAD_REQUEST error. Servlet writers who override this method should
read any data from the request (for example, form parameters), set entity
headers in the response, access the writer or output stream and, finally, write any
response data using the servlet output stream. The headers that are set should
include content type, and encoding.
req - HttpServletRequest that encapsulates the request to the servlet
resp - HttpServletResponse that encapsulates the response from the servlet
Throws: IOException
if detected when handling the request
Throws: ServletException
if the request could not be handled

4. doPut
protected void doPut(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
Performs the HTTP PUT operation; the default implementation reports an
HTTP BAD_REQUEST error. The PUT operation is analogous to sending a file
via FTP.
req - HttpServletRequest that encapsulates the request to the servlet
resp - HttpServletResponse that encapsulates the response from the servlet
Throws: IOException
if detected when handling the request
Throws: ServletException
if the request could not be handled
5. doDelete
protected void doDelete (HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
Performs the HTTP DELETE operation; the default implementation reports
an HTTP BAD_REQUEST error. The DELETE operation allows a client to
request a URI to be removed from the server.
req - HttpServletRequest that encapsulates the request to the servlet
resp - HttpServletResponse that encapsulates the response from the servlet
Throws: IOException
if detected when handling the request
Throws: ServletException
if the request could not be handled
6. doOptions
protected void doOptions(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
Performs the HTTP OPTIONS operation; the default implementation of this
method automatically determines what HTTP Options are supported. For
example, if a servlet writer subclasses HttpServlet and overrides the doGet
method, then this method will return the following header:
req - HttpServletRequest that encapsulates the request to the servlet
resp - HttpServletResponse that encapsulates the response from the servlet
Throws: IOException
if detected when handling the request
Throws: ServletException
if the request could not be handled
7. doTrace
protected void doTrace(HttpServletRequest req,
HttpServletResponse resp) 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. This method is not typically overridden.
req - HttpServletRequest that encapsulates the request to the servlet
resp - HttpServletResponse that encapsulates the response from the servlet
Throws: IOException
if detected when handling the request
Throws: ServletException
if the request could not be handled
8. service
protected void service(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
This is an HTTP-specific version of the Servlet.service method, which
accepts HTTP specific parameters. This method is rarely overridden. Standard
HTTP requests are supported by dispatching to Java methods specialized to
implement them.
Throws: IOException
if detected when handling the request
Throws: ServletException
if the request could not be handled
9. service
public void service(ServletRequest req,
ServletResponse res) throws ServletException, IOException
Implements the high level Servlet.service method by delegating to the
HTTP-specific service method. This method is not normally overriden.
Throws: IOException
if an I/O exception has occurred
Throws: ServletException
if a servlet exception has occurred
service in class GenericServlet
HttpSessionBindingEvent--This class implements the event that is
generated when an object is bound to or unbound from an HTTP session.
HttpUtils--The HttpUtils class provides the parseQueryString() method for
parsing a query string contained in an HTTP request.

Overriding the Destroy Method

When a server unloads a servlet, it calls the servlet's destroy method. The
destroy method should undo any initialization work and synchronize persistent
state with the current in-memory state.
For many servlets, however, there is initialization work that must be
undone. For example, assume there is a servlet that opens a database
connection during initialization. Its destroy method, shown as an example below,
would close that connection.
* Cleans up database connection
public void destroy() {
try {
catch (SQLException e) {
while(e != null) {
log("SQLException: " + e.getSQLState() + '\t' +
e.getMessage() + '\t' +
e.getErrorCode() + '\t');
e = e.getNextException();
} catch (Exception e) {
Providing Information about the Servlet
Some applets and applications, for example, the Java Web Server
Administration Tool, display information about a servlet. This information can
include a short description of the purpose of the servlet, its author, and perhaps
its version number. The Servlet API provides a method to return this information,
getServletInfo(). By default, this method returns null. While servlet writers are
not required to override this method, it is strongly recommended. The simple
servlet, shown as an example earlier, overrides this method:
* This is a simple example of an HTTP Servlet. It responds to the GET
* and HEAD methods of the HTTP protocol.
public class SimpleServlet extends HttpServlet {
public String getServletInfo() {
return "A simple servlet";

Coping with Service Threads at Servlet Termination

When a server removes a servlet, it typically calls destroy after all service
calls have been completed, or a server-specific number of seconds have passed,
whichever comes first. If your servlet has operations that take a long time to run
(that is, they may run longer than the server's grace period), then threads could
still be running when destroy is called. The servlet writer is responsible for
making sure that any threads still handling client requests complete.
A servlet with potentially long-running service requests should keep track
of how many service methods are currently running. Its long-running methods
should periodically poll to make sure that they should continue to run. If the
servlet is being destroyed, then the long-running method should stop working,
clean up if necessary, and return.
For example, the instance variable that counts the number of service
methods running could be called serviceCounter, and the indicator of whether the
servlet is being destroyed could be an instance variable called shuttingDown.
Each variable should have its own set of access methods:
public ShutdownExample extends HttpServlet {
private int serviceCounter = 0;
private Boolean shuttingDown;
//Access methods for serviceCounter
protected synchronized void enteringServiceMethod() {
protected synchronized void leavingServiceMethod() {
protected synchronized int numServices() {
return serviceCounter;
//Access methods for shuttingDown
protected setShuttingDown(Boolean flag) {
shuttingDown = flag;
protected Boolean isShuttingDown() {
return shuttingDown;
The service method should increment the service counter each time it is entered
and decrement it each time it returns:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException

try {
super.service(req, resp);
} finally {
The destroy method should check the serviceCounter, and if there are any
long-running methods, set the shuttingDown variable. This variable will let the
threads still handling client requests know that it is time to shut down. The
destroy method should then wait for the service methods to complete, in order to
provide a clean shutdown.
public void destroy() {
/* Check to see whether there are still service methods running,
* and if there are, tell them to stop. */
if (numServices() > 0) {
/* Wait for the service methods to stop. */
while(numService() > 0) {
try {
} catch (InterruptedException e) {

How to use servletrunner to Run a Servlet

Once you have written your servlet, you can run it in many web servers, or
in the servletrunner. Where ever you decide to run your servlet, there are certain
pieces of data that you might want or need to specify. When you are using
servletrunner you do this with properties.
The servletrunner is a small utility, intended for testing. It is multithreaded,
so it can run more than one servlet. It can be used, therefore, to run multiple
servlets simultaneously, or to test one servlet that calls other servlets in order to
satisfy client requests. Unlike some web servers, it does not automatically reload
servlets when they are updated. Because it is small, however, there is very little
overhead associated with stopping and restarting it in order to use a new version
of a servlet.
The servletrunner is in the <JDK>/bin directory. Invoking it with the -help
flag shows a usage message without running it:
% ./bin/servletrunner -help
Usage: servletrunner [options]
-p port the port number to listen on
-b backlog the listen backlog
-m max
maximum number of connection handlers
-t timeout connection timeout in milliseconds
-d dir
servlet directory
-r root document root directory
-s filename servlet property file name
verbose output
In order to see the default values of these options, you can call
servletrunner with the -v switch. This will, however, start the servlet runner. Just
stop it after you have obtained the information, if you are not ready to run it yet,
or want it to run with something other than the default values.
% ./bin/servletrunner -v
Server settings:
port = 8080
backlog = 50
max handlers = 100
timeout = 5000
servlet dir = .
document dir = .
servlet propfile =
Once the servletrunner is executing, you run servlets by calling them
directly in your browser, by using a form that calls a servlet to process its data.
The URL for a servlet has the following general form:

where servlet-name corresponds to the name you have given your servlet. For
example, to run the Phone Servlet, which has the property, you would use the following URL. (It assumes
that servletrunner is running on your machine, localhost, at port 8080, and that
the phone servlet is located in the servlet directory provided to servletrunner at
Another example, the survey servlet, is run as a result of submitting a form. The
URL used for the servlet by the survey-form in the HTML file is:

1. Write a servlet to design HTML page, with proper title, headings.
2. Write a servlet to check username & password passed from html page. If it
is Scott & tiger, display welcome message else show the same html
page again. [With res.sendRedirect (http://localhost:8080/login.html)]
3. WAP to accept two numbers from html display addition of them.
4. Write a Servlet to display html forms control names & their values.
5. Write Servlet to create html page for the feedback of product. Store the
feedback in a database.
6. Write a servlet to maintain a shopping cart, using session valriables.
7. Write a servlet to add a Cookie to clients machine that stores username,
current date & time. Display the same.
8. Write a servlet to accept a name of background color from user, change
the background color as per the color entered. [Design HTML using

Writing Thread Safe Servlets:

Ensuring two threads do not read or change data consistently. An
application is thread safe, if it always behaves predictably regardless of
number of concurrent threads running in its space.
Synchronization is a process of locking a variable, so that it can be read
and modified by only a single thread at a time. It eliminates race conditions by
locking variables for specified duration.
synchronized (this)
if (chkbal>=100)
{ // .code
pw.println (amount in checking-+chkbal);
It is possible to synchronize entire service () method. the form is:
HttpServletResponse res) throws ServletException, IOException


For declaring variables, the better place is within service method for multiclient application, because each call to service() is handled by a separate
thread, the variables will be protected( each request has its own copy) &
cannot be modified by other requests.
SingleThreadModel Interface:
Defines no methods & simply serves as a flag to server. If a servlet
implements this interface, server guarantees that no more than one thread
can execute service()/ doGet()/ doPost() methods a time for a particular
servlet instance.
import javax.servlet.*; import javax.servlet.http.*; import*;
public class greetings extends HttpServlet implements SingleThreadModel
String username;
public void service (HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
PrintWriter pw=res.getWriter();

username=req.getParamter (name);
pw.close ();
private void printgreeting(PrintWriter out)
out.println (Hello:+username);

Server-Sides includes:
It allows you to embed servlet calls withinan HTML document, using
<servlet>tag. These documents should use .shtml file extension. This
indicates to server that HTML includes SSI directives & should be passed to a
specialized SSI servlet for processing.
<servlet name=SERVLET_NAME
1. A servlet that returns a standard header.
import javax.servlet.*; import javax.servlet.http.*; import*;
public class hservlet extends HttpServlet
public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
res.setContentType (text/html);
PrintWriter pw=res.getWriter();
pw.println (<h1>Welcome</h1>);
pw.close ();

2. A servlet that returns a standard footer.

import javax.servlet.*; import javax.servlet.http.*; import*;
public class fservlet extends HttpServlet
public void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
res.setContentType (text/html);
PrintWriter pw=res.getWriter();
pw.println(<b>Copyright &copy2006, all rights reserved.</b>);
3. To add header & footer
<servlet code=hservlet></servlet>
Welcome to first HTML page containing header & footer.
<servlet code=fservlet></servlet>