From Twitter

SERVLET LIFE CYCLE with example

SERVLET LIFE CYCLE

After learning the basics of Servlet now, we shall study the life cycle of a Servlet.
Servlets are normal Java classes, which are created when needed and destroyed when
not needed. A Java Servlet has a lifecycle that defines how the Servlet is loaded and
initialized, how it receives and responds to requests, and how it is taken out of service.
In code, the Servlet lifecycle is defined by the javax.servlet.Servlet interface.
Since
Servlets run within a Servlet Container, creation and destruction of Servlets is the duty
of Servlet Container. Implementing the init() and destroy() methods of Servlet
interface allows you to be told by the Servlet Container that when it has created an
instance of your Servlet and when it has destroyed that instance. An important point to
remember is that your Servlet is not created and destroyed for every request it
receives, rather it is created and kept in memory where requests are forwarded to it
and your Servlet then generates response. We can understand Servlet Life Cycle

There are three principal stages in the life of a Java servlet, namely:

1) Servlet Initialisation: In this first stage, the servlet’s constructor is called
together with the servlet method init( )this is called automatically once during
the servlet’s execution life cycle and can be used to place any one-off
initialisation such as opening a connection to a database.

So you have created your Servlet class in above-mentioned example, by extending the
HttpServlet class and have placed it in /WEB-INF/classes/ directory of your
application. Now, when will Servlet Container create an instance of your Servlet?
There are a few situations:

• When you have specifically told the Servlet Container to preload your Servlet
when the Servlet Container starts by setting the load-on-startup tag to a nonzero
value e.g.

<web-app>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>com.stardeveloper.servlets.TestServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
</web-app>

So, when the Servlet Container starts it will preload your Servlet in the memory.
• If your Servlet is not already loaded, its instance will be created as soon as a
request is received for it by the Servlet Container.
• During the loading of the Servlet into the memory, Servlet Container will call
your Servlet's init() method.

2) Servlet Execution: Once your Servlet is initialised and its init() method called,
any request that the Servlet Container receives will be forwarded to your
Servlet’s service() method. HttpServlet class breakes this service() method into
more useful doGet(), doPost(), doDelete(), doOptions(), doPut() and doTrace()
methods depending on the type of HTTP request it receives. So in order to
generate response you should override the doGet() or doPost() method as per
your requirement.
At this moment all the requests will be forwarded to the appropriate doGet() or
doPost() or whatever method as required. No new instance will be created for
your Servlet.
When a Servlet request is made to the Servlet engine, the Servlet engine
receives all the request parameters (such as the IP address of client), user
information and user data and constructs a Servlet request object, which
encapsulates all this information.
Another object, a Servlet response object is also created that contains all the
information the Servlet needs to return output to the requesting client.

3) Servlet Destruction: When your application is stopped or Servlet Container
shuts down, your Servlet's destroy() method will be called to clean up any
resources allocated during initialisation and to shutdown gracefully. Hence, this
acts as a good place to deallocate resources such as an open file or open
database connection.

Point to remember: init() and destroy() methods will be called only once during the life time of the Servlet while service() and its broken down methods (doGet(),
doPost() etc ) will be called as many times as requests are received for them by the
Servlet Container.

Let us understand all the phases of Servlet Life Cycle with the help of an example:

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet {
private String name = "saurabh Shukla";
public void init() throws ServletException
{
System.out.println("Calling the method TestServlet : init");
}
public void destroy()
{
System.out.println("Calling the method TestServlet : destroy");
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// print content
out.println("<html><head>");
out.println("<title>TestServlet ( by ");
out.println( name );
out.println(" )</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>TestServlet ( by ");
out.println( name );
out.println(" ) :</p>");
out.println("</body></html>");
out.close();
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
doGet(req, res);
}
}

Our TestServlet is extremely simple to demonstrate the life cycle of a Servlet, which
is displaying the name of the author to the user. We override four methods of
HttpServlet class. init() is called by the Servlet Container only once during the
initialization of the Servlet. Similarly destroy() is called once when removing the
Servlet instance. We can thus put initialisation code in init() method. doGet() is called
when a GET client request is received and doPost() is called when POST client
request is received. In the doGet() method we set the content type to ‘text/html’
(telling the client browser that it is an HTML document). Then get hold of PrintWriter
object and using it print our own HTML content to the client. Once done we close() it.
Now, we will compile this Servlet in the same manner as we have compiled earlier:

C:\jakarta-tomcat-4.0-b5\webapps\star\WEB-INF\classes\com\stardeveloper\servlets>javac       TestServlet.java

If all goes well a 'TestServlet.class' file will be created in that folder. Now, open your
browser and point to the following address:
http://localhost:8080/star/servlet/com.stardeveloper.servlets.TestServlet
You should see response from the Servlet showing “TestServlet”.

No comments:

Post a Comment

Labels

(MCS-031 (6) 2011 (5) 4nf (1) 5nf (1) ACCESS CONTROL In Relational Database (1) ALGORITHMICS (5) assignment 2014 2015 (1) AVAILABLE TOOLS & ALGORITHMS (5) BCA (1) BINARY SEARCH (1) Block Nested Loop Join (1) Build and Fix Model (1) BUILDING BLOCKS OF ALGORITHMS (1) CHARACTERISTICS OF AN ALGORITHM (2) Core Java (1) Data Communication Network Security (1) DATABASE SECURITY (1) EER tool (1) ELEMEMTARY ALGORITHMICS (2) ENHANCED ER TOOLS (1) EVOLUTION (1) EXAMPLE OF AN ALGORITHM (2) Indexed Nested-Loop Join (1) install servelet engine (1) INTRODUCTION (1) Iterative Enhancement Model (1) Java Server Pages (1) JDBC (1) JSP (2) LEVELS OF DATABASE SECURITY (1) MCA (9) MCA 051 (1) MCA 3rd Semester (8) MCA 4th Semester (1) MCA 5 sem (1) MCS-031 (7) MCS-031 : DESIGN AND ANALYSIS OF ALGORITHM (14) MCS-032 (1) MCS-033 (1) MCS-034 (2) MCS-035 (1) mcs-041 (2) MCS-042 (1) mcs-043 (2) mcs-052 solved assignment (1) MCSL-036 (2) Nested loop join (1) OBJECTIVES (1) Operating System (2) OUTLINE OF ALGORITHMICS (1) Principles of Management and Information Systems (1) PROBLEMS (1) QUERY PROCESSING AND EVALUATION (1) Query processing Optimisation (1) Question Papers (8) Related Topic (9) relational Database (1) SELECT OPERATION Query Processing (1) Servlet (1) Servlet Programme (1) Servlet Programming (1) SOFTWARE DEVELOPMENT MODELS (4) SOFTWARE ENGINEERING (4) Solution (7) Solved Assignment 2013 2014 (6) SOME PRE-REQUISITES AND Asymptotic Bounds ASYMPTOTIC BOUNDS INTRODUCTION (1) STATISTICAL DATABASE SECURITY (1) structure (1) SUMMARY (1) Waterfall Model (1) Write a C program to print the following triangle (1)