You are on page 1of 11

CHAPTER 3

Servlet
Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side
programming language. However, there were many disadvantages to this technology.
We have discussed these disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.

What is a Servlet?
Servlet can be described in many ways, depending on the context.
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic
web page.

CGI (Common Gateway Interface)


CGI technology enables the web server to call an external program and pass HTTP
request information to the external program to process the request. For each request,
it starts a new process.

Compiled By: Vinod Mahajan


Disadvantages of CGI
There are many problems in CGI technology:
1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start
processes.
3. It uses platform dependent language e.g. C, C++, perl.

Advantages of Servlet

There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the Servlet. Threads have many benefits over the
Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low. The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.

Architecture of Servlet
The following diagram shows the servlet architecture:

Compiled By: Vinod Mahajan


In Web communication, the client and server uses Web (Internet) as an interface
(medium) of communication. That is, both client and server should connect to Web
(though an Internet Service Provider) to communicate, else, impossible to
communicate. When connected, the simple client system can be called as "Web client"
and the server can be called as "Web server".
The standard protocol used in the Web, now-a-days, is HTTP (HyperText Transfer
Protocol) protocol. For this reason, the cleint and server are also can be called as "HTTP
client" and "HTTP server".
When connected, the client sends a request and server responses. In Web
terminology, use only the words of request and response only. It is known as
request/response paradigm (style).

Servlet architecture includes:


a) Servlet Interface
To write a servlet we need to implement Servlet interface. Servlet interface can be
implemented directly or indirectly by extending GenericServlet or HttpServlet class.

b) Request handling methods


There are 3 methods defined in Servlet interface: init(), service() and destroy().

The first time a servlet is invoked, the init method is called. It is called only once during
the lifetime of a servlet. So, we can put all your initialization code here.

To send a request, the software to be loaded on the Web cleint is "Browser". Similarly,
the software required on the Web server is "Web server software".
Responsibilities of Web client
a) Should be able to take request from the client by displaying some GUI
environment (like user name and passowrd as in Login screen).
b) To extract the data entered by the user and send it to the Web server as request.
c) Should be able to receive what the server responses and display to the user.
Responsibilities of Web server
a) Should be able to receive the request send by the Web client.

Compiled By: Vinod Mahajan


b) As per the request, load an appropriate servlet, execute it and send the output
of execution as response to client.
c) When response is delivered close the connection.

API
You need to use Servlet API to create servlets. There are two packages that you must
remember while using API, the javax.servlet package that contains the classes to
support generic servlet (protocol-independent servlet) and
the javax.servlet.http package that contains classes to support http servlet. You may
be wondering what is generic and http servlet.
Let’s see the hierarchy of packages:
java.lang.Object
|_extended byjavax.servlet.GenericServlet
|_extended byjavax.servlet.http.HttpServlet
Every Servlet must implement the java.servlet.Servlet interface, you can do it by
extending one of the following two
classes: javax.servlet.GenericServlet or javax.servlet.http.HttpServlet. The first one is
for protocol independent Servlet and the second one for http Servlet.

Generic Servlet
As I mentioned above, if you are creating a Generic Servlet then you must
extend javax.servlet.GenericServlet class. GenericServlet class has an abstract service()
method. Which means the subclass of GenericServlet should always override the
service() method.
Signature of service() method:
public abstract void service(ServletRequest request, ServletResponse response)
throws ServletException, java.io.IOException
The service() method accepts two arguments ServletRequest object and
ServletResponse object. The request object tells the servlet about the request made
by client while the response object is used to return a response back to the client.

HTTP Servlet
If you creating Http Servlet you must extend javax.servlet.http.HttpServlet class, which
is an abstract class. Unlike Generic Servlet, the HTTP Servlet doesn’t override the
service() method. Instead it overrides one or more of the following methods. It must
override at least one method from the list below:

Compiled By: Vinod Mahajan


• doGet() – This method is called by servlet service method to handle the HTTP GET
request from client. The Get method is used for getting information from the
server
• doPost() – Used for posting information to the Server
• doPut() – This method is similar to doPost method but unlike doPost method
where we send information to the server, this method sends file to the server,
this is similar to the FTP operation from client to server
• doDelete() – allows a client to delete a document, webpage or information from
the server
• init() and destroy() – Used for managing resources that are held for the life of the
servlet
• getServletInfo() – Returns information about the servlet, such as author, version,
and copyright.
In Http Servlet there is no need to override the service() method as this method
dispatches the Http Requests to the correct method handler, for example if it receives
HTTP GET Request it dispatches the request to the doGet() method.

Life Cycle of Servlet


A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.
• The servlet is initialized by calling the init() method.
• The servlet calls service() method to process a client's request.
• The servlet is terminated by calling the destroy() method.
• Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in detail.
The init() Method
The init method is called only once. It is called only when the servlet is created, and
not called for any user requests afterwards. So, it is used for one-time initializations,
just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first
started.
When a user invokes a servlet, a single instance of each servlet gets created, with each
user request resulting in a new thread that is handed off to doGet or doPost as
appropriate. The init() method simply creates or loads some data that will be used
throughout the life of the servlet.
The init method definition looks like this −
Compiled By: Vinod Mahajan
public void init() throws ServletException {
// Initialization code...
}
The service() Method
The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from
the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread
and calls service. The service() method checks the HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
The service () method is called by the container and service method invokes doGet,
doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with
service() method but you override either doGet() or doPost() depending on what type
of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service
request. Here is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has
no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

Compiled By: Vinod Mahajan


The destroy() Method
The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup
activities.
After the destroy() method is called, the servlet object is marked for garbage collection.
The destroy method definition looks like this −
public void destroy() {
// Finalization code...
}
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
• First the HTTP requests coming to the server are delegated to the servlet
container.
• The servlet container loads the servlet before invoking the service()
method.
• Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance
of the servlet.

Compiled By: Vinod Mahajan


Session Tracking in Servlets
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking
techniques. Each time user requests to the server, server treats the request as the new
request. So we need to maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown
in the figure given below:

Why use Session Tracking?


To recognize the user It is used to recognize the particular user.
Session Tracking Techniques
There are two techniques used in Session tracking:
1. Cookies
2. HttpSession

Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests.
A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add
cookie with response from the servlet. So cookie is stored in the cache of the browser.

Compiled By: Vinod Mahajan


After that if request is sent by the user, cookie is added with request by default. Thus,
we recognize the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides
a lot of useful methods for cookies.
Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.

Compiled By: Vinod Mahajan


Method Description

public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot be
changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods
provided by other interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is
used to add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to
return all the cookies from the browser.

How to create Cookie?


Let's see the simple code to create cookie.
1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
2. response.addCookie(ck);//adding cookie in the response

How to delete Cookie?


Let's see the simple code to delete cookie. It is mainly used to logout or signout the
user.
1. Cookie ck=new Cookie("user","");//deleting value of cookie
2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response

How to get Cookies?


Let's see the simple code to get all the cookies.

Compiled By: Vinod Mahajan


1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and val
ue of cookie
4. }

HttpSession interface
In such case, container creates a session id for each user.The container uses this id to
identify the particular user.An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.
How to get the HttpSession object ?
The HttpServletRequest interface provides two methods to get the object of
HttpSession:
1. public HttpSession getSession():Returns the current session associated with this
request, or if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession
associated with this request or, if there is no current session and create is true,
returns a new session.
Commonly used methods of HttpSession interface
1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a
request associated with this session, as the number of milliseconds since
midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound
to it.

********

Compiled By: Vinod Mahajan

You might also like