In this tutorial you will learn about the servlet life example which shows how the methods of life cycle are called
Servlet Cycle Simple Example
Every servlet have their own life cycle in which they perform their task. Every servlet calls init(), service(), and destroy() method in their life cycle. If you do not write init() and destroy() the container call it implicitly. An example of servlet life cycle is given below.
ServletLifeCycleExample.java
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 { \// Servlet init() method public void init() { System.out.println("\n\n Servlet Init() Method"); System.out.println("Servlet Initialised by init() method"); } public void init(ServletConfig config) { try { super.init(config); System.out.println("\n\nServlet init(config)method\n"); System.out.println("Servlet Initialised by init(context) method"); } catch (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); out.println("Servlet Life Cycle Example"); System.out.println("Inside doGet() method"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void destroy() { System.out.println("\n\nServlet destroyed \n"); System.out.println("Servlet Finalising by destroy() method"); } }
When you run this application it will display message as shown below:
On Browser
On Tocat Console....
[ 0 ] Comments