Introduction
The javax.servlet.Servlet interface defines the three methods as
- public void init(ServletConfig config)
- public void service( ServletRequest req, ServletResponse res)
- public void destroy()
Can a servlet contain constructor?
A servlet class can contain any type of constructors. The servlet container calls only the default constructor of the servlet class. The parameterized constructor cannot be called by the servlet container but these can be called by the default constructor by using this keyword.
Program
- import javax.servlet.*;
- import javax.servlet.http.*;
- import java.io.*;
- /* Execute this in tomcat 4.1 to get the o/p in console window */
- public class lifecycle extends HttpServlet
- {
- public lifecycle(int x)
- {
- System.out.println("from constructor");
- }
- public void init()
- {
- System.out.println("Servlet Started Its Execution");
- }
- public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
- {
- res.setContentType("text/html");
- Thread th=Thread.currentThread();
- System.out.println("new user arrived..");
- PrintWriter out=res.getWriter();
- out.println("<html><body bgcolor='pink'>");
- out.println("<h1 align='center'>Yur thread name is : "+th.getName()+"</h1>");
- out.println("</body></html>");
- }
- public void destroy()
- {
- System.out.println("servlet gets out...");
- }
- }

Join the conversation! Your thoughts help the community grow.