Pages

Thursday, February 21, 2013

Servlet Interface, Methods and Important Notes about Servlets


Servlet is an interface available in two packages javax.servlet.*; and javax.servlet.http;
Servlets are generally implemented using 3 ways:


1. By implementing the Servlet interface.
                public class ServletExample implements Servlet {}
2. Extending the GenericServlet Class.
                public class ServletExample extends GenericServlet {}
3. Extending the HttpServelet Class.
                public class ServletExample extends HttpServlet {}

PS: Servlet API is available in the Java EE API.

Five major interfaces in the javax.servlet.* package are Servlet, ServletRequest, ServletResponse, ServletConfig, ServletContext.

Methods in Servlet interface. There are 5 methods in Servlet interface which are:
  1. 1.       void init(ServletConfig sc) - Executed only once when the project is deployed and takes ServletConfig object as the parameter.
  2. 2.       void service(ServletRequest req, ServletResponse res) - Only method where logic of the program is written and is executed by the servlet like we have run() in Threads. Takes ServletRequest and ServletResponse reference objects as the parameters.
  3. 3.       void destroy() - Used to destroy the servlet and is done by the server automatically on removal of the project.
  4. 4.       String getServletInfo() - returns a String type value.
  5. 5.       ServletConfig getServletConfig() - returns a ServletConfig Object.

Servlet interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:
  • ·         The servlet is constructed, and then initialized with the init method.
  • ·         Any calls from clients to the service method are handled.
  • ·         The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.

Read the next post to know how to Deploy a Project and Servlet in the Server.

0 comments:

Post a Comment