Hi All,

Greetings of the day!

Today we will explore servlet in-depth with examples so let's get started.

What is a servlet?

The servlet is a java program used to create a web application that process request from the web using HTTP protocols and the servlet runs within a servlet container i.e. web servers like tomcat.

Servlet is an interface in java that is implemented by HttpServlet  & GenericServlet. GenericServlet is protocol independent whereas HttpServlet is specific for HTTP protocol for a web application.

Servlet instance is created by the servlet container and for each request new thread is created instead of a new instance or process. 

Servlet Lifecycle 

Servlet lifecycle includes below 3 methods which are called by the servlet container.

  1. init() - init method is called only once by the servlet container after a new servlet instance is created. init method is to do initialization post-construction of servlet
  2. service() - service method is called by container for each request received from web and service method then called doGet() or doPost or other HTTP methods based on HTTP request method received by container from the web.
  3. destroy() - destroy method is called only once by servlet container before removing servlet from the container.
The below diagram shows the complete lifecycle of the servlet. 


Example of servlet / How to create a servlet  

 There are two ways to create a servlet here I am using eclipse IDE.

  • Right-click on src/main/java and select new -- servlet provides package detail & class name  then click on next 

It will ask you to select HTTP methods you like to create as shown below and then click on finish.

Once you click on the finish you can see below mapping added in web.xml by IDE


Also, BrandController.java is created by IDE which will extend the HttpServlet

so when get/post request is received by servlet container with mapping /BrandController it will call above method and execute logic we have written.
  • Second way to create servlet  is to create a java class let's say we created StudentCotroller,java then we need to follow below 2 step to make Student Controller a servlet which can handle request
    • StudentController.java should extends HttpServlet class and we need to override doGet/doPost based on our requirement.
    • We need to add mapping for StudentController and specify it as servlet class in web.xml as shown below


so tomcat will ask StudentController to handle any request from the web with mapping /student. We can see the same mapping is automatically added by IDE when we use option 1 to create a servlet.

So we have explored what is servlet and how we can create servlet & servlet lifecycle. If you have any doubts feel free to comment.

Other articles you may like to visit 




Thanks
Happy Learning!