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.
- 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
- 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.
- destroy() - destroy method is called only once by servlet container before removing servlet from the container.
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
- 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
0 Comments
If you have any doubts let me know.