In the life cycle of servlet there are three important methods. These methods are
Life cycle of Servlet |
- The client enters the URL in the web browser and makes a request. The browser then generates the HTTP request and sends it to the Web server.
- Web server maps this request to the corresponding servlet.
- The server basically invokes the init() method of servlet. This method is called only when the servlet is loaded in the memory for the first time. Using this method initialization parameters can also be passed to the servlet in order to configure itself.
- Server can invoke the service for particular HTTP request using service() method. The servlets can then read the data provided by the HTTP request with the help of servlet() method.
- Finally server unloads the servlet from the memory using the destroy() method.
import javax.servlet.*;
import javax.servlet.http*;
import java.io.*;
public class LifeCycle extends GenericServlet
{
public void init(ServletConfig config) throws ServletException
{
System.out.println("init");
}
public void service(ServletRequest request, ServletResponse responses) throws ServletException, IOException
{
System.out.println("from service");
PrintWriter out = response.getWrite();
out.println("Twinkle Twinkle little stars.");
out.print("How I wonder whst you are.");
}
public void destroy()
{
System.out.println("destroy");
}
}
In the above program we have first of all used an init() method to which object of the ServletConfig interface is passed. This interface allows the servlet to get the initialization parameters.
Then we have used the service() method to which the ServletRequest and ServletResponse parameters are passed for making the HTTP request and getting the HTTP response from the servlet. The output stream is created using getWriter() and along this output stream some messages are written. These messages will then be displayed on the web browser when the servlet gets executed.
Finally the destroy() function is written in order to unload the servlet from the memory.
0 comments:
Post a Comment