Java Servlet Life Cycle Example
Servlets are modules of the Java code that run on a server application to answer the client requests. They are not tied to a specific client-server protocol but are most commonly used with HTTP and the word “Servlet” is often used in the meaning of “HTTP Servlet“. In this tutorial, we will explain the Servlet Lifecycle.
Servlet is a Java program which exists and executes in the J2EE servers and is used to receive the HTTP protocol request, to process it and send back the response to the client. Servlets make use of the Java standard extension classes in the packages
javax.servlet.http. Since Servlets are written in the highly portable Java language and follow a standard framework, they provide a means to create the sophisticated server extensions in a server and operating system independent way.
Typical uses for HTTP Servlets include:
- Processing and/or storing the data submitted by an HTML form
- Providing dynamic content i.e. returning the results of a database query to the client
- Managing state information on top of the stateless HTTP i.e. for an online shopping cart system which manages the shopping carts for many concurrent customers and maps every request to the right customer
As Servlet technology uses the Java language, thus web applications made using Servlet are Secured, Scalable, and Robust.
1.1 Servlet Architecture & Lifecycle
A Servlet, in its most general form, is an instance of a class which implements the
javax.servlet.Servlet interface. Most Servlets, however, extend one of the standard implementations of this interface, namely
javax.servlet.http.HttpServlet. In this tutorial we’ll be discussing only HTTP Servlets which extends the
In order to initialize a Servlet, a server application loads the Servlet class and creates an instance by calling the no-args constructor. Then it calls the Servlet’s
init(ServletConfig config) method. The Servlet should perform the one-time setup procedures in this method and store the
ServletConfig object so that it can be retrieved later by calling the Servlet’s
getServletConfig() method. This is handled by the
GenericServlet. Servlets which extend the
GenericServlet (or its subclass i.e.
HttpServlet) should call the
super.init(config) at the beginning of the
init method to make use of this feature.
Signature of init() method
public void init(ServletConfig config) throws ServletException
ServletConfig object contains the Servlet parameters and a reference to the Servlet’s
init method is guaranteed to be called only once during the Servlet’s lifecycle. It does not need to be thread-safe because the
service() method will not be called until the call to the
init() method returns.
When the Servlet is initialized, its
service(HttpServletRequest req, HttpServletResponse resp) method is called for every request to the Servlet. The method is called concurrently (i.e. multiple threads may call this method at the same time) as it should be implemented in a thread-safe manner. The
service() method will then call the
doPost() method based on the type of the HTTP request.
Signature of service() method
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
When the Servlet needs to be unloaded (e.g. because a new version should be loaded or the server is shutting down), the
destroy() method is called. There may still be threads that execute the
service() method when the
destroy() method is called, so
destroy() method has to be thread-safe. All resources which were allocated in the
init() method should be released in the
destroy() method. This method is guaranteed to be called only once during the Servlet’s lifecycle.
Signature of destroy() method
public void destroy()
1.2 Servlet Container
Servlet Container is a component which loads the Servlets and manages the Servlet life cycle and responds back to the dynamic content to the HTTP server. Servlet container is used by the HTTP server for processing the dynamic content and Tomcat is a perfect example of the Servlet Container.
The Servlet Container performs operations that are given below:
- Life Cycle Management
- Multithreaded Support
- Object Pooling
- Security etc.
1.3 Get vs. Post Request
There are many differences between the HTTP Get and Post request. Let’s see these differences:
|Sending of data||Client data is appended to URL and sent||Client data is sent separately|
|Storing in the Browser History||As data is appended, the client data is stored in the browser history||As data is sent separately, the client data is not stored in the browser history|
|Bookmark||The URL with client data can be bookmarked. Thereby, later without filling the HTML form, the same data can be sent to server||Not possible to bookmark|
|Encoding or enctype||application/x-www-form-urlencoded||application/x-www-form-urlencoded or multipart/form-data. For binary data, multipart enctype to be used|
|Limitation of data sent||Limited to 2048 characters (browser dependent)||Unlimited data|
|Hacking easiness||Easy to hack the data as the data is stored in the browser history||Difficult to hack as the data is sent separately in an HTML form|
|Type of data sent||Only ASCII data can be sent||Any type of data can be sent including the binary data|
|Data secrecy||Data is not secret as other people can see the data in the browser history||Data is secret as not stored in the browser history|
|When to be used||Prefer when data sent is not secret. Do not use for passwords etc.||Prefer for critical and sensitive data like passwords etc.|
|Cache||Can be caught||Cannot be caught|
|Default||If not mentioned, GET is assumed as default||Should be mentioned explicitly|
|Performance||Relatively faster as data is appended to URL||A separate message body is to be created|
Do remember, if client data includes only the ASCII characters i.e. no secrecy and data are limited to 2 KB length, then prefer GET, else POST.
1.4 Servlet Advantages
There are many advantages of Servlet over CGI (Common Gateway Interface). The Servlet Web Container creates threads for handling the multiple requests to the Servlet. Threads have a lot of benefits over the processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The basic benefits of Servlet are as follows:
- Less response time because each request runs in a separate thread
- Servlets are scalable
- Servlets are robust and object-oriented
- Servlets are platform-independent
- Servlets are secure and offer portability
That’s all for this post. Happy Learning!!
In this section, developers learned the Servlet Lifecycle. I hope this article served you with whatever developers were looking for.