Posts Tagged Servlets

The life cycle of servlet

Tags: , , ,

Life cycle of servlet from the perspective of the container

1. After start, the container is looking for servlet classes in the appropriate directory (for Apache Tomcat would be $ TOMCAT_HOME / webapps) .

2. Once they are found, there are two possible ways: servlets are loaded immediately or only when someone wants to use them. By using term “load servlet” I mean the execution of its constructor and init () method. init () is executed only once in the life cycle of servlet . It allows you to prepare it for usage (eg to connect to the database, initialize any resources).

Code below presents fragment of web.xml file allowing to define order in which servlets are loaded when the containter starts:

<web-app>
    ...
    <servlet>
        <servlet-name>FirstToLoadServlet</servlet-name>
        <servlet-class>pl.tdziurko.scwcd.servlets.FirstToLoadServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet>
        <servlet-name>SecondToLoadServlet</servlet-name>
        <servlet-class>pl.tdziurko.scwcd.servlets.SecondToLoadServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    ...
</web-app>

Continue reading this post …


Be Sociable, Share!

Servlets – family of classes and interfaces

Tags: , , ,

Today I am going to present the most important methods, classes and interfaces in the Servlet API.

public interface Servlet

Main interface from which all starts. It defines key methods for the life cycle of servlet:


public void init(ServletConfig config) throws ServletException;
public ServletConfig getServletConfig();
public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException;

public void destroy();

and one additional method


public String getServletInfo();

which should return information about servlet (version, author, resposibility, etc.) Continue reading this post …


Be Sociable, Share!