Life cycle of servlet


init()
The servlet is constructed, then initialized with the init method, this process will happen only once when the servlet is loaded

service()
Any calls from clients to the service method are handled. This process will happen every time a servlet receives a new request.

destroy()
The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.

Example
Servlet code
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;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
		System.out.println("init called");
	}

	public Login() {
		// TODO Auto-generated constructor stub
		System.out.println("creating servlet Object");

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("Login servlet Get called");
		
		response.setContentType("text/html");
		PrintWriter pw=response.getWriter();
				
		pw.write("<b>Login servlet Get called</b> <br>");
		pw.write("Try reloading the page again and check the console to see how servlet life cycle works");
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
		System.out.println("destroy called");
	}

}

Output:
Run the application and try reloading the page to see the difference

creating servlet Object
init called
Login servlet Get called
Login servlet Get called

Screen shot
            
            

Download
Lifecycle example war
Lifecycle example zip



Related Post

Comments


©candidjava.com