Servlet is a server Java class that runs in a web container and is used to create Web applications. It is mostly used to build dynamic web pages. Web applications built using servlets are scalable and robust. Each request to servlet runs in a separate thread.
See below picture for communication between web browser and a server.
A server for example, Apache Tomcat is a servlet container, which implements the J2EE Servlet specifications. It enables us an environment to run the servlets.
Servlet Life Cycle:
Servlet class is first loaded when the 1st request for the servlet is received by the web container.
Once the servlet is loaded by the container an instance of it is created.
init() method is called by the container on the servlet instance to initialize the servlet.
service() method: the container calls the service method each time the request for the servlet is received.
destroy() method : the container calls the destroy method before removing the servlet. Any clean-up code generally goes here.