You are on page 1of 7

1

What is Servlet?
Servlet is a Java programming language class that provides a component-based, platformindependent method to create web based applications to enhance the functionality of web server.
Or The Servlet is a class that is written in Java programming language and is used to provide a
mechanism for developing server side programs. It interacts with clients via request-response
programming model. Servlet enhance the web servers by extending the applications hosted by it.
For such applications, Java Servlet technology defines HTTP-specific servlet classes.
Servlet invokes a single thread for each user request rather than creating a new process every
time. Servlet is highly portable, is platform independent, is highly secure and has Java database
connectivity.
1. History of Web application
Earlier in client- server computing, each application had its own client program and it worked as
a user interface and need to be installed on each user's personal computer.
2. Introduction to Web Server
A web server is the combination of computer and the program installed on it. Web server
interacts with the client through a web browser. It delivers the web pages to the client and to an
application by using the web browser and the HTTP protocols respectively. We can also define
the web server as the package of large number of programs installed on a computer connected to
Internet or intranet for downloading the requested files using File Transfer Protocol, serving email and building and publishing web pages. A web server works on a client server model. A
computer connected to the Internet or intranet must have a server program.
Web Server is a computer on the World Wide Web that stores Html documents that can be
retrieved via a Web browser. It is a computer that delivers web pages.
3. What is a Container
Container are nothing but a Java application which controls servlets. Tomcat is one of the
example of a container. It is the container which calls the servlet's methods like doPost() and
doGet().
A web container, which is a component of a web server, is used to interact with servlet. It is also
manages the lifecycle of servlets and maps a URL to a particular servlet.
In the client-side programming paradigm, program/scripts are downloaded, interpreted and
executed by the browser. CGI is one of the important server-side programming techniques. The
CGI connects a web server to an external application.
Types of Server Side Programs
Active Server Pages (ASP), Java Servlets, Java Server Pages (JSPs), Enterprise Java Beans
(EJBs) and PHP.
Languages for CGI C/C++, Perl, TCL(tool command language),python and unix/linux shell

Learn Servlet Life Cycle

Servlet is a Java programming language class that provides a component-based, platformindependent method to create web based applications to enhance the functionality of web server.
If we talk about Servlet Life Cycle, we would need to cover the entire process starting from its
initialization till the destruction which is basically wrapped in four stages that are:
Loading and Instantiation
Initialization
Servicing the Request
Destroying the Servlet
1. Loading and Installation:
This is the initial stage of Servlet Life Cycle in which servlet container loads the servlet from
web.xml, which is done either during initiation or when the first request is made. If the attribute
<load-on-startup> of web.xml file has a positive value then theServlet will be loaded else it will
load when the first request comes for service. After loading of the servlet, the container creates
the instances of the Servlet by usingClass.forName(ServletName).newInstance().
2. Initialization:
Once the instances are created the second stage called Initialization begins in which theservlet
container calls the init() method and passes the servlet initialization parameters to
the init() method. One thing that is to be known is, the init() must be called by theservlet
container prior to the Servlet can serve any request. The initialization parameter continues until
the Servlet is destroyed. The init() method is called only once during the entire life cycle of the
servlet. The servlet will only be available for service if it is servlet code is loaded successfully
without any error otherwise it will be not available for service.
3. Servicing the Request:
Once the initialization process has been completed successfully, the Servlet becomes available
for service. Moreover, servlet creates a separate thread for each of the request made and the
the servlet container calls the service() method for servicing any request. The service() method
evaluates the kind of request and calls the suitable method (doGet() or doPost()) to execute the
request and send response to the client using the methods of the response object.
4. Destroying the Servlet:
If the Servlet is no longer needed to serve any request further, the servlet containercalls for
the destroy() method. Like the init() method this destroy() method is also called only once in the
entire life cycle of the servlet. Once the destroy() method is called, it indicates to the servlet
container not to send any request for service and theServlet releases all the resources related to
it. Java Virtual Machine is responsible for the memory associated with the resources for
garbage collection.

For complete Servlet Life Cycle Example:


The Life Cycle of Servlet having some good characteristics that allows servlet to address both
performance and resource problems of CGI along-with security pertains of low-level Server API
programming. The life cycle of a servlet is operated by the container in which the servlet has
been deployed. Servlet life cycle is categorized into 4 parts i.e. Instantiation, Initialization,
Servicing
the
Request/Implementation
&
Destruction.
Example of the Servlet having all parts of its lifecycle:
package roseindia.net;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletLifeCycleExample extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException
{
System.out.println("init() method is called ");
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("service() method called");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}

public void destroy()


{
System.out.println("Servlet is destroying....");
}
}
Servlet mapping for the above example
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>servletLifeCycleExample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ServletLifeCycleExample</servlet-name>
<servlet-class>roseindia.net.ServletLifeCycleExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletLifeCycleExample</servlet-name>
<url-pattern>/servlet</url-pattern>
</servlet-mapping>
</web-app>
Advantages of Java Servlets
1.
2.
3.
4.
5.
6.
7.

Portability
Powerful
Efficiency
Safety
Integration
Extensibilty
Inexpensive Each of the points are defined below:

Portability
As we know that the servlets are written in java and follow well known standardized APIs so
they are highly portable across operating systems and server implementations. We can develop a
servlet on Windows machine running the tomcat server or any other server and later we can
deploy that servlet effortlessly on any other operating system like Unix server running on the

iPlanet/Netscape Application
(WORA) program.

server.

So

servlets

are write

once,

run

anywhere

Powerful
We can do several things with the servlets which were difficult or even impossible to do with
CGI, for example the servlets can talk directly to the web server while the CGI programs can't
do. Servlets can share data among each other, they even make the database connection pools easy
to implement. They can maintain the session by using the session tracking mechanism which
helps them to maintain information from request to request. It can do many other things which
are difficult to implement in the CGI programs.
Efficiency
As compared to CGI the servlets invocation is highly efficient. When the servlet get loaded in the
server, it remains in the server's memory as a single object instance. However with servlets there
are N threads but only a single copy of the servlet class. Multiple concurrent requests are handled
by separate threads so we can say that the servlets are highly scalable.
Safety
As servlets are written in java, servlets inherit the strong type safety of java language. Java's
automatic garbage collection and a lack of pointers means that servlets are generally safe from
memory management problems. In servlets we can easily handle the errors due to Java's
exception handling mechanism. If any exception occurs then it will throw an exception.
Integration
Servlets are tightly integrated with the server. Servlet can use the server to translate the file paths,
perform logging, check authorization, and MIME type mapping etc.
Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it stands today, the
servlet API support Http Servlets, but in later date it can be extended for another type of servlets.
Inexpensive
There are number of free web servers available for personal use or for commercial purpose. Web
servers are relatively expensive. So by using the free available web servers you can add servlet
support to it.
Servlets are server side components that provides a powerful mechanism for developing
server web applications for server side.
Advantages of Servlets over CGI
Servlets are server side components that provides a powerful mechanism for developing server
web applications for server side. Earlier CGI was developed to provide server side capabilities to

the web applications. Although CGI played a major role in the explosion of the Internet, its
performance, scalability and reusability issues make it less than optimal solutions. Java Servlets
changes all that. Built from ground up using Sun's write once run anywhere technology java
servlets provide excellent framework for server side processing.
Using servlets web developers can create fast and efficient server side applications and can run it
on any servlet enabled web server. Servlet runs entirely inside the Java Virtual Machine. Since
the servlet runs on server side so it does not depend on browser compatibility.

Servlets have a number of advantages over CGI and other API's. They are:
1. Platform Independence
Servlets are written entirely in java so these are platform independent. Servlets can run on any
Servlet enabled web server.
2. Performance
Due to interpreted nature of java, programs written in java are slow. But the java servlets runs
very fast. These are due to the way servlets run on web server. For any program initialization
takes significant amount of time. But in case of servlets initialization takes place first time it
receives a request and remains in memory till times out or server shut downs.
3. Extensibility
Java Servlets are developed in java which is robust, well-designed and object oriented
language which can be extended or polymorphed into new objects. So the java servlets take all
these advantages and can be extended from existing class to provide the ideal solutions.
4. Safety
Java provides very good safety features like memory management, exception handling etc.
Servlets inherits all these features and emerged as a very powerful web server extension.
5. Secure
Servlets are server side components, so it inherits the security provided by the web server.
Servlets are also benefited with Java Security Manager.
How to Run a Servlet
To run a servlet one should follow the steps illustrated below:
Download and Install the tomcat server:Install the tomcat server in a directory in which you
want to install and set the classpath.for the variable JAVA_HOME in the environment
variable. To get details about the installation process and setting the classpath click the link
Tomcat installation.

Set the class for the jar file: Set the classpath of the servlet-api.jar file in the
variableCLASSPATH inside the environment variable by using the following steps.
For Windows XP, Go to Start->Control Panel->System->Advanced->Environment Variables>New button and Set the values as
Variable Name: CLASSPATH
Variable Value: C:\Program Files\Java\Tomcat 6.0\lib\servlet-api.jar
For Windows 2000 and NT Go to Start->Settings->Control Panel->System->Environment
Variables->New button and Set the values as
Variable Name: CLASSPATH
Variable Value: C:\Program Files\Java\Tomcat 6.0\lib\servlet-api.jar
Create a java source file and a web.xml file in a directory structure.
Compile the java source file, put the compiled file (.class file) in the classes folder of your
application and deploy the directory of your application in the webapps folder inside the
tomcat directory.

Start the tomcat server, open a browser window and type the
URLhttp://localhost:8080/directory (folder name of your application) name/servler
nameand press enter.
If everything is correct your servlet will run.

You might also like