To get started with Servlets, let’s first start with a simple Servlet application i.e LifeCycle application, that will demonstrate the implementation of the init(), service() and destroy() methods.
First of all it is important to understand that if we are developing any Servlet application, it will handle some client’s request so, whenever we talk about Servlets we need to develop a index.html page (can be any other name also) which will request a particular Servlet to handle the request made by the client (in this case index.html page).
To be simple, lets first describe the steps to develop the LifeCycle application :
- Creating the index.html page
- Creating the LifeCycle Servlet
- Creating deployment descriptor
Creating the index.html page
For the sake of simplicity, this page will just have a button invoke life cycle. When you will click this button it will call LifeCycleServlet (which is mapped according to the entry in web.xml file).
The name of the Servlet is given in action attribute of form tag to which the request will be send on clicking the button, in this case FirstServlet.
Creating the Servlet (FirstServlet)
Now, its time to create the LifeCycleServlet which implements init(), service() and destroy() methods to demonstrate the lifecycle of a Servlet.
Creating deployment descriptor(web.xml)
As discussed in other posts about web.xml file we will just proceed to the creation of it in this article.
To know the working and use of the above web.xml file its recommended to read the next post.
How to run the above program ?
It is important to make sure that you have some server like Apache Tomcat installed and configured with the IDE of your choice like Netbeans.
Now, if the above condition is fullfilled then you can simply create the above three files under Web application project and then simply run the above application.
First of all the index.html file gets executed and then when the button is clicked the request goes to the Servlet, in this case LifeCycleServlet and the service() method handles the request.
When the above invoke life cycle servlet button is clicked the code under service() method of LifeCycleServlet is executed and the below output is obtained :
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.