Skip to main content

Java Servlet Life Cycle

Life Cycle of a Servlet (Servlet Life Cycle)


Servlet class is loaded.The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:

  1. Servlet instance is created.
  2. init method is invoked.
  3. service method is invoked.
  4. destroy method is invoked.
Life cycle of a servlet

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When the web container invokes the destroy() method, it shifts to the end state.


1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container.


2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle.


3) init method is invoked

The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:
  1. public void init(ServletConfig config) throws ServletException  

4) service method is invoked

The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below:

  1. public void service(ServletRequest request, ServletResponse response)   
  2.   throws ServletException, IOException  

5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below:

  1. public void destroy()  

Steps to create a servlet example


The servlet example can be created by three ways:There are given 6 steps to create a servlet example. These steps are required for all the servers.

  1. By implementing Servlet interface,
  2. By inheriting GenericServlet class, (or)
  3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request specific method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:

  1. Create a directory structure
  2. Create a Servlet
  3. Compile the Servlet
  4. Create a deployment descriptor
  5. Start the server and deploy the project
  6. Access the servlet

1)Create a directory structures

The directory structure defines that where to put the different types of files so that web container may get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's see the directory structure that must be followed to create the servlet.

directory structure of servlet

As you can see that the servlet class file must be in the classes folder. The web.xml file must be under the WEB-INF folder.


2)Create a Servlet

There are three ways to create the servlet.
  1. By implementing the Servlet interface
  2. By inheriting the GenericServlet class
  3. By inheriting the HttpServlet class
The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests such as doGet(), doPost, doHead() etc.
In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice that get request is the default request.

DemoServlet.java
  1. import javax.servlet.http.*;  
  2. import javax.servlet.*;  
  3. import java.io.*;  
  4. public class DemoServlet extends HttpServlet{  
  5. public void doGet(HttpServletRequest req,HttpServletResponse res)  
  6. throws ServletException,IOException  
  7. {  
  8. res.setContentType("text/html");//setting the content type  
  9. PrintWriter pw=res.getWriter();//get the stream to write the data  
  10.   
  11. //writing html in the stream  
  12. pw.println("<html><body>");  
  13. pw.println("Welcome to servlet");  
  14. pw.println("</body></html>");  
  15.   
  16. pw.close();//closing the stream  
  17. }}  

3)Compile the servlet

For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files:

Jar fileServer
1) servlet-api.jarApache Tomcat
2) weblogic.jarWeblogic
3) javaee.jarGlassfish
4) javaee.jarJBoss

Two ways to load the jar file

  1. set classpath
  2. paste the jar file in JRE/lib/ext folder

Put the java file in any folder. After compiling the java file, paste the class file of servlet in WEB-INF/classes directory.


4)Create the deployment descriptor (web.xml file)

The deployment descriptor is an xml file, from which Web Container gets the information about the servet to be invoked.

The web container uses the Parser to get the information from the web.xml file. There are many xml parsers such as SAX, DOM and Pull.

There are many elements in the web.xml file. Here is given some necessary elements to run the simple servlet program.


web.xml file
  1. <web-app>  
  2.   
  3. <servlet>  
  4. <servlet-name>sonoojaiswal</servlet-name>  
  5. <servlet-class>DemoServlet</servlet-class>  
  6. </servlet>  
  7.   
  8. <servlet-mapping>  
  9. <servlet-name>sonoojaiswal</servlet-name>  
  10. <url-pattern>/welcome</url-pattern>  
  11. </servlet-mapping>  
  12.   
  13. </web-app>  

Description of the elements of web.xml file

There are too many elements in the web.xml file. Here is the illustration of some elements that is used in the above web.xml file. The elements are as follows:


<web-app> represents the whole application.
<servlet> is sub element of <web-app> and represents the servlet.
<servlet-name> is sub element of <servlet> represents the name of the servlet.
<servlet-class> is sub element of <servlet> represents the class of the servlet.
<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.

5)Start the Server and deploy the project

To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin directory.


One Time Configuration for Apache Tomcat Server

You need to perform 2 tasks:

  1. set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).
  2. Change the port number of tomcat (optional). It is required if another server is running on same port (8080).

1) How to set JAVA_HOME in environment variable?

To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment variables.

Go to My Computer properties -> Click on advanced tab then environment variables -> Click on the new tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk folder in variable value -> ok -> ok -> ok.

Go to My Computer properties:

configuring apache tomcat 1

Click on advanced system settings tab then environment variables:

configuring apache tomcat 2

configuring apache tomcat 3

Click on the new tab of user variable or system variable:

configuring apache tomcat 4

Write JAVA_HOME in variable name and paste the path of jdk folder in variable value:

configuring apache tomcat 2

There must not be semicolon (;) at the end of the path.


After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin.
Note: There are two types of tomcat available:
  1. Apache tomcat that needs to extract only (no need to install)
  2. Apache tomcat that needs to install
It is the example of apache tomcat that needs to extract only.

how to start tomcat server for servlet program

how to start tomcat server for servlet program


Now server is started successfully.

2) How to change port number of apache tomcat

Changing the port number is required if there is another server running on the same system with same port number.Suppose you have installed oracle, you need to change the port number of apache tomcat because both have the default port number 8080.

Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory . Change the Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us replace it by 9999 and save this file.


5) How to deploy the servlet project

Copy the project and paste it in the webapps folder under apache tomcat.

how to deploy servlet in apache tomcat server

But there are several ways to deploy the project. They are as follows:

  • By copying the context(project) folder into the webapps directory
  • By copying the war folder into the webapps directory
  • By selecting the folder path from the server
  • By selecting the war file from the server

Here, we are using the first approach.

You can also create war file, and paste it inside the webapps directory. To do so, you need to use jar tool to create the war file. Go inside the project directory (before the WEB-INF), then write:

  1. projectfolder> jar cvf myproject.war *  

Creating war file has an advantage that moving the project from one location to another takes less time.


6) How to access the servlet

Open broser and write http://hostname:portno/contextroot/urlpatternofservlet. For example:

  1. http://localhost:9999/demo/welcome  

output of servlet example





Anurag Rana

Comments

Popular posts from this blog

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

Standard and Formatted Input / Output in C++

The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming. C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called   input operation   and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called   output operation . Standard Input and Output in C++ is done through the use of  streams . Streams are generic places to send or receive data. In C++, I/O is done through classes and objects defined in the header file  <iostream> .  iostream  stands for standard input-output stream. This header file contains definitions to objects like  cin ,  cout , etc. /O Library Header Files There are following header files important to C++ pro