A Java Servlet is a special Java program that extends the functionalities of a server. A web server communicates with the Servlet through a web container. The web container creates an instance of the Servlet,invokes callback methods on the Servlet, executes and destroys the Servlet.
A Servlet can only comprehend objects therefore the web container converts http requests into valid request object and for each incoming request a thread is spawn to handle the request. The web container knows which Servlet handles an incoming request by referencing its main file which is the deployment descriptor(web.xml).
The web.xml specifies the Servlets in web application and there mappings. lets take an example of a login Servlet, its deployment descriptor is as follows:
<webapp> <servlet> </servlet><servlet -name>login</servlet> <servlet -class>login</servlet> <servlet -mapping> </servlet><servlet -name>login</servlet> <url -pattern>/login</url> </webapp>
The Servlet element contains the Servlet name which is basically the Servlet’s Java class name and the Servlet class which is file path in which the Servlet reside.The Servlet mapping element maps the Servlet to the URL specified in the URL pattern element.
As mentioned previously, a Servlet has its methods. These methods are:
init(): initiliazes Servlet before handling client requests
service(): determines which http method to invoke on the Servlet class based on the request
doPost():handles the business logic
destroy():discards the Servlet
This basically covers almost everything there is on Java Servlets.
Posted by Jerono Tembu