Showing posts with label Servlet Life Cycle. Show all posts
Showing posts with label Servlet Life Cycle. Show all posts

Saturday, 29 March 2014

Servlets : ServletLifeCycle - Example

Enjoying Java & Servlet Tutorials?

Subscribe to Ram N Java for in-depth, beginner-friendly programming guides!

Subscribe Now

Understanding the Servlet Life Cycle in Java

In Java web development, understanding the life cycle of a Servlet is fundamental. The entire life cycle of a Servlet is managed by the Servlet Container (such as Apache Tomcat) and consists of three core methods: init(), service(), and destroy().

1. Initialization Phase: init()

The init() method is invoked by the container strictly once when the Servlet instance is first loaded and instantiated. This phase initializes necessary resources, configurations, or database connections before handling client requests.

2. Request Processing Phase: service()

Once initialized, the service() method is executed multiple times—each time a client sends a request to the mapped URL pattern. It reads incoming client requests and generates dynamic responses back to the browser.

3. Destruction Phase: destroy()

The destroy() method is called by the container strictly once when the Servlet is taken out of service or the server is shutting down. This allows clean-up operations like closing database connections or releasing system memory.


Related Tutorials from the Channel


Click here to watch in Youtube : https://www.youtube.com/watch?v=6AcVTFcZkCk

Click the below Image to Enlarge

ServletInterface Project Dir Structure
ServletLifeCycle - Example

ServletsLifeCycle.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Extend HttpServlet class
public class ServletsLifeCycle extends HttpServlet
{

  private static final long serialVersionUID = 1L;
  private int i;

  public void init() throws ServletException
  {
    System.out.println("------------------------------------------------------");
    System.out.println(" Init method is called ");
    System.out.println("------------------------------------------------------");
  }

  public void service( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
                  IOException
  {
    ++i;
    System.out.println(" service method is called "+i+ " time");
    // Set response content type
    response.setContentType("text/html");

    // Actual logic goes here.
    PrintWriter out = response.getWriter();
    out.println("<h1>" + " service method is called "+i+ " time" + "</h1>");
  }

  public void destroy()
  {
    System.out.println("------------------------------------------------------");
    System.out.println(" destroy method is called ");
    System.out.println("------------------------------------------------------");
  }
}

web.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

    <display-name>ServletsLifeCycle Application</display-name>
    <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>

     <servlet>
        <servlet-name>ServletsLifeCycle</servlet-name>
        <servlet-class>ServletsLifeCycle</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ServletsLifeCycle</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    
</web-app>


index.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!DOCTYPE HTML><html lang="en"><head>
<meta charset="UTF-8">
<title>ServletsLifeCycle</title>
</head>
<body>
<p>
<h3>ServletsLifeCycle</H3>
<p></p>
<ul>
<li><a href="hello">ServletsLifeCycle Test</a></li>

</ul>
</body></html>

Environment Used

JDK version :1.6.0_30
Tomcat version : 7.0.50 

To Download HelloworldApp Project Click the below link

https://sites.google.com/site/javaee4321/servlets/ServletsLifeCycleApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Monday, 3 March 2014

    Servlets Life Cycle

    Master Java Web Development!

    Subscribe to Ram N Java for easy-to-follow Java & Web Technology tutorials!

    Subscribe Now

    The Complete Guide to the Java Servlet Life Cycle

    A Java Servlet is a server-side component responsible for receiving client requests and returning dynamic web pages. Managing these components efficiently is handled entirely by the Servlet Container (such as Apache Tomcat or Jetty). The container controls the entire journey of a Servlet from the moment it is loaded into memory until it is completely unloaded.

    Step 1: Loading and Instantiation

    Before any request is handled, the Servlet container loads the compiled .class file into memory and creates a single instance of the Servlet using its default no-argument constructor.

    Step 2: Initialization with init()

    Right after instantiation, the container calls the init(ServletConfig config) method. This method runs only once during the lifecycle of the Servlet. It is designed to perform one-time startup tasks like reading configuration parameters or setting up database pools.

    Step 3: Handling Requests with service()

    Every time a client makes a request (such as GET or POST), the web container spawns a separate worker thread and invokes the service(ServletRequest, ServletResponse) method. It determines the HTTP request type and routes it to appropriate methods such as doGet() or doPost().

    Step 4: Clean-up and Destruction with destroy()

    When the application is stopped, undeployed, or the web server is shutting down, the container invokes the destroy() method. This executes only once, giving the Servlet an opportunity to close open connections, stop background threads, and free up system resources.


    Related Tutorials from the Channel



    Click here to watch in Youtube :
    https://www.youtube.com/watch?v=JtQ3uaHvPkc


    Click the below Image to Enlarge
    Servlets Life Cycle

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Tutorials