Monday, May 4, 2015

Servlet Interface

The javax.servlet.Servlet is the base interface of Java Servlet API. Servlet interface declares the
life cycle methods of servlet. All the servlet classes are required to implement this interface. The methods declared in this interface are:
public abstract void init(ServletConfig paramServletConfig) throws ServletException – This
is the very important method that is invoked by servlet container to initialize the servlet and
unless ServletConfig parameters. The servlet is not ready to process client request until init()
method is finished executing. This method is called only once in servlet life cycle and make
Servlet class different from normal java objects. We can extend this method in our servlet classes
to initialize resources such as DB Connection, Socket c connection etc.

public abstract ServletConfig getServletConfig() – This method returns a servlet config object,
which contains any initialization parameters and startup configuration for this servlet. We can use
servlet this method to get the init parameters of servlet defines in deployment descriptor (web.xml) or
through annotation in Servlet 3. We will look into ServletConfig interface later on.

public abstract void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException – This method is responsible for processing the client request.

Whenever servlet container receives any request, it creates a new thread and execute the
service() method by passing request and response as argument. Servlets usually run in multi-
threaded environment, so it’s developer responsibility to keep shared resources thread-safe using
synchronization.
public abstract String getServletInfo() – This method returns string containing information
about the servlet, such as its author, version, and copyright. The string returned should be plain
text and can’t have markups.
public abstract void destroy() – This method can be called only once in servlet life cycle and
used to close any open resources. This is like finalize method of a java class.


No comments:

Post a Comment

Contact Form

Name

Email *

Message *