Java Servlet
Q1. What is the Lifecycle of Java Servlet?
Java Servlet has a pre-defined lifecycle starting from initializer (memory allocation) until the object is destructed (memory deallocated). It takes place in following steps :
- init() – is called as soon as the request is received by the web server and a new servlet instance is initialized.
- service() – to handle client request and redirect the request to an appropriate doGet() or doPost()
- destroy() – called when the request is handled, response sent back to the client and finally the memory allocated to the servlet is deallocated.
Q2. How to configure a Java Servlet?
Configuration of Java Servlet is defined inside a deployment descriptor file – web.xml. Although, it is legacy now as most servlet based applications nowadays used Annotation based configuration to configure a Java Servlet using @WebServlet Annotation.
Example : @WebServlet(name = “MyServlet”, urlPatterns = “/myServlet”)
Q3. What is a Servlet Filter?
A Servlet Filter is an additional component for performing pre-post processing work on the web requests like logging, monitoring, debugging and troubleshooting.
Introduction to Java Servlets
Today, we all are aware of the need to create dynamic web pages i.e. the ones that can change the site contents according to the time or can generate the content according to the request received from the client. If you like coding in Java, then you will be happy to know that using Java there also exists a way to generate dynamic web pages and that way is Java Servlet. But before we move forward with our topic let’s first understand the need for server-side extensions.