Newsletter

Example on Servlet Life Cycle in Java

Servlets » on Jan 10, 2013 { 16 Comments } By Sivateja

Let us see one example on servlet life cycle. Do you have any doubts related to the concept ? if so please check this Servlet Life Cycle theory article before you execute this example.

Files required

  • ServletLifeCycle.java
  • web.xml

Directory Structure

ServletLifeCycle.java

package java4s;

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 ServletLifeCycle extends HttpServlet
{

	public ServletLifeCycle()
	{	
		System.out.println("Am from default constructor");
	}

	public void init(ServletConfig config)
	{
		System.out.println("Am from Init method...!");
	}

	public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
	{	
		res.setContentType("text/html");
		PrintWriter pw = res.getWriter();
		pw.println("I am from doGet method");
		pw.close();
	}	

	public void destroy()
	{
		System.out.println("Am from Destroy methods");
	}

}

web.xml

<web-app>
      <servlet>
            <servlet-name>second</servlet-name>
            <servlet-class>java4s.ServletLifeCycle</servlet-class>
         <load-on-startup>1</load-on-startup>
      </servlet>

      <servlet-mapping>
            <servlet-name>second</servlet-name>
            <url-pattern>/lifecycle1</url-pattern>
      </servlet-mapping>
</web-app>

Execution Flow

  • Right click on your project ‘root(project folder)’ > Run as > click on ‘Run on Server
  • Then eclipse will open an internal web browser with URL  —  http://localhost:2013/Servlet-Life-CycleExample/
  • Now just append our project folder name to that URL, so the final URL will be like http://localhost:2013/Servlet-Life-CycleExample/Servlet-Life-CycleExample
  • Press enter, now you will be able to see the output

Flow

  • When ever you hit the final URL (http://localhost:2013/Servlet-Life-CycleExample/Servlet-Life-CycleExample), servlet container will first loads web.xml and check the value in <url-pattern> tag [ line number 10, we have given the pattern name as /lifecycle1 ]
  • Immediately it will check the value in <servlet-name> tag [line number 9, we have given second]
  • Now it will search for the same value second in <servlet-name> under <servlet> tag [that’s what we have in line number 3 ]
  • So value of <servlet-name> under <servlet-mapping> & <servlet> are same [in this case @ line numbers 9,3 ]
  • If so container will load java class given in <servlet-class> tag [line number 4, our class name is java4s.ServletLifeCycle ]
  • Finally servlet container came to ‘ServletLifeCycle‘ class, it will executes init() method first (only once) > then service() or doGet() or doPost() method [ in our case doGet() ]
  • Finally destroy() method will be executed before our object get garbage collected.

Hope i explained properly, you understand right :-), i will explain <load-on-startup> later just forget as of now.

 Output

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

16 Responses to “Example on Servlet Life Cycle in Java”
  1. hello friend pls keep JSP and JDBC pls

  2. ram lende says:

    what is difference between GenericServlet and HttpServlet

  3. vinod says:

    What about destroy()??

  4. mukul says:

    Indian always rocks, thanks a lot Sivateja.

  5. Jayshri says:

    one doubt please

    application is 24×7 in that case how servlet works and when it is call destroy() method and when it is garbage collected?

  6. sravani says:

    Thanks a lot Sivateja.Excellent website that i have ever seen.can you
    please update the remaining topics ASAP.i’m eagerly waiting…….!

  7. Mani Kant Nigam says:

    Suppose there are two servlet deployed on server. When client sends request for one servlet firstly servlet will be loaded,instantiated and initialized using init method, then service method and then destroy.

    That mean if next time request came for same servlet, it will take less time to create response. Am i right?

    And what would be the step if i send request for another servlet? same like loading, instantiation,initialization, service and destroy or only service and destry?

    Please help me resolve my confusion about servlet.

  8. Suren says:

    In the execution flow, “Now just append our project folder name to that URL, so the final URL will be like http://localhost:2013/Servlet-Life-CycleExample/Servlet-Life-CycleExample” where do u want us to do it in the webbrowser opened by eclipse or any other browser on my machine.

  9. Lutuf Ali says:

    Sir i am very happy for visit your web. sir i want know that is it posible to make a executable setup for my servlet web project?

  10. Poonam Singh says:

    Excellent

  11. Qadeer says:

    sir please i want to learn MySql,Oracle and jsp

  12. vimal says:

    What happens when there are three request comes simultaneously? Each time init method called? Destroy() method called for every request?

  13. Satya says:

    Above example you used constructor,so can you tell me when this constructor will get executed,and why you used constructor.

  14. Kamesh says:

    What is meant by init(ServletConfig config) servlet config

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.