Servlet Life Cycle
When a client computer sends a request to a server, in simple terms, when you type in a URL on your browser, the request ultimately reaches another computer, the 'server', which serves the particular web page you requested.
A Servlet is a program that runs on a web server and can process your request and send the right content back. These programs have a life cycle from creation to destruction.
Introduction to Servlet
When we search Google for scaler.com, we request that a server render Scaler's web page. Handling such requests and rendering web pages dynamically can be done using Java Servlets.
So, what exactly are servlets? Java Servlets (also known as Jakarta Servlets) are server-side programs that run on a web server. They act as a middle layer between client requests and the web server's database/applications.
They are used to host web applications on servers and mostly support all client-server protocols. The architecture of the servlet is as follows:
Client/Browser: The client through the browser sends HTTP requests to the webserver.
Web Server: Includes several components to control access to files hosted on the server. A basic HTTP server will comprehend URLs and follow HTTP protocol to deliver the contents of hosted websites.
Web Container: This web server component interacts with Java servlets. It manages the servlets' life cycle, including loading and unloading, managing request and response objects, and URL mapping on the server-side. Ex: Tomcat.
Servlet Life Cycle
Servlet Life Cycle can be described as a series of steps that a servlet goes through during its life span from loading to destruction.
The Servlet Life Cycle is as follows:
- Servlet class is loaded first when the Web container receives a new request.
- Then, the web container creates a servlet instance. This instance is created only once in the entire Servlet Life Cycle.
- The servlet is initialized using the init() method.
- the servlet calls service() method to process the client's request.
- The server is destroyed using the destroy() method.
- Java Virtual Machine's(JVM) garbage collector clears the destroyed servlet's memory.
Let us see the signature for each of the methods mentioned above:
init()
Whenever a user invokes the URL associated with the particular servlet, the init() method is called. It is called only once, not each time a request is made. An instance of a servlet is created through the init() method. Each user request creates a new thread catering to GET and POST requests.
service()
The web container calls the service() method each time there is a new request to the servlet. This is done by spawning a new thread. This method checks the HTTP request type, i.e, whether it is a GET, POST, DELETE, etc, and calls the doGet, doPost, doDelete, etc methods as per the request.
destroy()
This method is called just once at the end of the Life Cycle of Servlet. It helps perform all the clean-up activities, including closing database connections and halting background threads. Then, the servlet is removed from the container.
Architecture Diagram of the Servlet Life Cycle in Java
The following represents the Servlet Life Cycle. When a request is sent for a particular web page, the corresponding servlet must be initialized. The servlet container/web container will load the servlet and create an instance of it through init().
Subsequent requests to the same web page will invoke the service() method. This method will typecast the ServletRequest and ServletResponse objects to HttpServletRequest and HttpServletResponse objects, respectively. Servlets can handle multiple requests concurrently since each request results in a new thread.
The destroy() method is only called once all threads within the servlet's service methods have exited or after a timeout period.
Program Illustrating Java Servlet Implementation
A program illustrating Java Servlet implementation We can implement a Servlet in the following ways:
- By implementing Servlet interface
- By extending GenericServlet class
- By extending HttpServlet class
The easiest and most common way is to extend the HTTPServlet class. Let's see a servlet's Hello World program using this method.
The HttpServlet class is extensively used to create servlets since it provides methods to handle HTTP requests like doGet(),doPost, doDelete(), etc. The above code is used to display HTML content on the web page displaying "Hello World".
Features of Java Servlet Life Cycle
1. Portable
Java's portability comes from the fact that It is portable. This means that the Java code is compiled into bytecode, which is platform-independent. Hence, it is Write Once Run Anywhere(WORA).
2. Efficient
Efficient because it creates a new thread for each request and not each process.
3. Scalable
Due to multithreading, Servlets can handle multiple requests and are scalable to be quite responsive. Servlets are also amenable to various load distribution architectures. With the right load distribution, we can easily scale web applications.
4. Robust
JVM handles all the Servlet programs, including garbage collection and memory leaks prevention.
Java Servlet Request
The job of a servlet is to handle the request and reply with a response. To handle the client request, Java provides two interfaces named ServletRequest and HTTPServletRequest. Both these interfaces have several methods that can allow us to get information from the request. Let us look at the various HTTPRequest interfaces.
1. HTTP Request Header
HTTP Request header is used to pass additional information about the client/requestor to the server. These include extra information and metadata that the server can use. HTTPServletRequest provides getHeaderNames() and getHeader() methods, which can be used to extract header names and header values. Let us see some of the common header names sent:
Accept: This specifies the acceptable media types in the response.
Accept-Charset: This indicates the acceptable character sets in the response. E.g., ISO-8859-1
Accept-Encoding: This restricts the content-coding values that are acceptable in the response.
Accept-Language: preferred set of language in response.
Authorization: This type indicates that the user agent is attempting to authenticate itself with a server.
User-Agent: This type contains information about the user agent who originated the request.
Content-Length: for POST messages, the length of data attached.
Cookie: From the Email address of the requester. Only used by custom clients, not by browsers.
Host: Host and port as listed in the original URL.
2. HTTP Request Parameters
HTTP Request parameters are ways in which clients can send user information to the server. Parameters can be sent in the URL or even in the request body. Any word after the '?' in a URL contains parameters. For Example: www.site.com?myparam1={id1}&myparam2={id2} myparam1 and my param2 are the parameters in the above URL request. We can access the parameters from a request in the following way using getParameter().
Typically, if an HTTP GET request is sent along with the parameters in the query string in the URL. Whereas, if it is an HTTP POST request, the parameters are included in the HTTP request body part.
3. HTTP Request InputStream
An HTTP Post request can send a lot of data to the server in the request body. We can access all these data using InputStream pointing to the request body.
This will return the raw data from the request, which can be separately parsed and used as necessary.
4. HTTP Request Context
When' deployed, ' the web container creates a ServletContext object. This object can be used to retrieve metadata about the web application stored in the web.xml file.
As you can see, you first have to get the session object to access the ServletContext object.
5. HTTP Request Session
A session can hold the details about a user between requests across the application. An HTTPSession object is used for session management. When a new user accesses the application for the first time, the HTTPSession object is obtained through request.getSession().
To identify the session, a user is given a unique ID t. A session is active until a specified timeout value is mentioned in the web.xml file. Let us see the code snippet to create a session:
Session user information can be accessed/modified using setAttribute and getAttribute as follows:
Java Servlet Response
Let us explore the HTTP Response object, which is used to send appropriate data from server to client.
1. HTTP Response Header
Headers in response must be set before writing data into it. You can set it as a key-value pair in the following way-
2. HTTP Response Content Type
This is a header used to tell the browser the kind of data being returned. The default for servlets is text/plain, but text/HTML is usually explicitly specified. This header can be set in the following way-
3. HTTP Response Content Length
Content length is used to tell the browser how many bytes are being sent by the servlet. This is needed only when the browser is using a persistent HTTP connection.
4. HTTP Response Write HTML
In order to send HTML as a response back to the browser, we need to use PrintWriter.
5. HTTP Response Redirection
Redirection is used when we need to direct users to a location other than the requested one. This can happen when the document is moved to a different location. We can do this by using the following code in doGet()/doPost() method:
Benefits of Servlets
Easy to implement
It is wasy to implement Servlet using Java APIs. It is also easy to implement sessions and cookies since dedicated interfaces are provided for each use case.
Easy Database Connection
Using' CGI', we could not connect to the database directly. However, using Servlets, we can connect to the database directly and track sessions.
Protocol Independent
Servlets are flexible to follow any web protocol, including FTP, and HTTP.
Better Exception Handling
Earlier, CGI(Common Gateway Interface) scripts, which were used before Servlets and written in C++, did not have good exception handling. For instance, the application might crash if there was a divide by 0 error. Servlets, written in Java, have much better ways to handle such exceptions and ensure the application doesn't crash. They also have provisions for redirection and forwarding.
Security
The server-side components inherit the security of the webserver. And the Servlet programs benefit from Java's Security Manager.
Conclusion
- Java Servlets are server-side programs that handle and respond to client requests to a web application through the browser.
- Life Cycle of Servlet consists mainly of three methods - init(), service(), and destroy().
- HTTP requests from clients/browsers can be read. This includes cookies, parameters, and session handling.
- HTTP response from the server is sent can be sent to the client in various forms, including text, documents, HTML, binary, etc.
- Servlets can handle multiple requests concurrently through multithreading. Each new request spawns a new thread, which consumes less space than creating a new process.
- JVM's garbage collector handles stale data and prevents memory leaks.