Introduction To Java Servlets and Its Life-Cycle

What is a Java Servlet?

What is Java Servlet

A servlet in Java is a class that enhances server functionalities, supporting applications accessed via a request-response model. Servlets, integral to Java programming, typically bolster web server applications by handling various types of requests, although they are most noted for their role in web applications. This versatility makes Java servlets a cornerstone in developing dynamic web content.

What is Java Servlet

There are several varieties of interfaces and classes available in the Servlet API. Some of them are as follows:

  • HTTP Servlet
  • Generic Servlet
  • Servlet Request
  • Servlet Response

With the definition, interfaces, and classes of Java Servlets discussed, we will now advance into our next topic, learning about the Java Servlet's Architecture.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Java Servlet Architecture

Java Servlet Architecture

We can also consider the software architecture of a servlet as the life cycle of the Java Servlet. To write a Servlet, the user needs first to implement the Servlet Interface, directly or indirectly, using the following import command.

import javax.servlet.*;

Once the Servlet interface is imported, and we inherit the HTTP Class, we begin with the Java Servlet's life cycle.

In the life cycle of a servlet, we have mainly three stages, which are mentioned below.

  • init()
  • service()
  • destroy()

We call these methods at their respective stages. The methods are resolved by generating the essential threads for the process to get executed.

Next, we will learn the Life-Cycle of a Java Servlet in a detailed manner. 

Java Servlet Life-Cycle

The Java Servlet Life cycle includes three stages right from its start to the end until the Garbage Collector clears it. These three stages are described below.

  1. init()
  2. service()
  3. destroy()

1. init()

The init() is the germinating stage of any Java Servlet. When a URL specific to a particular servlet is triggered, the init() method is invoked.

Another scenario when the init() method gets invoked is when the servers are fired up. With every server starting up, the corresponding servlets also get started, and so does the init() method.

One important specialty of the init() method is the init() method only gets invoked once in the entire life cycle of the Servlet, and the init() method will not respond to any of the user's commands.

The init() method Syntax:

public void init() throws ServletException {

//init() method initializing  

}

2. service()

The service() method is the heart of the life cycle of a Java Servlet. Right after the Servlet's initialization, it encounters the service requests from the client end.

The client may request various services like:

  • GET
  • PUT
  • UPDATE
  • DELETE

The service() method takes responsibility to check the type of request received from the client and respond accordingly by generating a new thread or a set of threads per the requirement and implementing the operation through the following methods.

  • doGet() for GET
  • doPut() for PUT
  • doUpdate() for UPDATE
  • doDelete() for DELETE

The service() method Syntax:

public void service(ServletRequest request, ServletResponse response) 

throws ServletException, IOException {

}

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

3. destroy()

Like the init() method, the destroy() method is also called only once in the Java Servlet's entire life cycle. 

When the destroy() method is called, the Servlet performs the cleanup activities like,

  • Halting the current or background threads
  • Making a recovery list of any related data like cookies to Disk.

After that, the Servlet is badged, ready for the Garbage collector to have it cleared.

The destroy() method Syntax:

public void destroy() {

//destroy() method finalizing 

}

Finishing with the life cycle of the Java Servlet, we are now advancing further, where we encounter the Java Servlet features.

Learn top skills demanded in the industry, including Angular, Spring Boot, Hibernate, Servlets, and JSPs, as well as MVC, web services, and SOA to build highly web scalable apps with the Full Stack Java Developer Masters Program.

Java Servlet Features

The Java Servlets carry over the features of Java Programming Language. The key features offered by the Java Servlets are as follows.

  • Portable
  • Efficient 
  • Scalable
  • Robust

1. Portable

As discussed above, the servlets feature the same Portable nature as the Java Programming Language. The Servlet program designed in one Operating System's Platform can be run in a different Operating System Platform with ease.

2. Efficient 

The Java Servlet, by its nature, provides an instantaneous response to the client's request. Also, it can be portable and perform in every environmental condition regardless of the operating system platform.

3. Scalable

We consider Java Servlets to be highly scalable. Servlets use completely lightweight threads for the processes and can simultaneously handle multiple client requests by generating various threads.

4. Robust

The Java Servlets are best known for their robust operating procedures. The servlets extend the features of Java, which include.

  1. Java Security Manager
  2. Java Garbage Collector
  3. Exception Handling.

Implementation of these advanced features makes Java Servlets resilient to any security threats to a decent extent. Also, the garbage collector takes care of memory management and eliminates the issues related to memory management in real-time, leaving Servlets to be Robust.

Followed by the features of Java Servlets, we will dive into the Servlet Request and Response Phases.

Java Servlet Request

The Java Servlets operate in the form of Requests and Responses. The first phase is the request from the user's end. The HttpRequest object represents the HTTP request to a browser that the user sends to the web application. Thus, anything the browser sends is accessible through the HttpRequest.

Now, we will learn about the various segments of a request received by the Servlet.

  1. HTTP Request Header
  2. HTTP Request Parameters
  3. HTTP Request InputStream
  4. HTTP Request Context
  5. HTTP Request Session

1. HTTP Request Header

The request headers are key-value pairs sent as a request by the browser, along with the HTTP request. The request headers contain information about what browser software is being used, what file types the browser can receive. 

2. HTTP Request Parameters

Along with the request, the browser shares a few parameters related to the information required. Request parameters are technically a crucial part of the URL of an HTTP request. 

3. HTTP Request InputStream

HTTP Request InputStream is an ordered stream of input data. The HTTP Request InputStream extends the java.io.InputStream library.

4. HTTP Request Context

We dedicate the HTTP Request Context to storing the metadata related to the application.

5. HTTP Request Session

The session object holds information about a specific user in between multiple requests. In case you set a new object during the session object request, the object will get available for you to access during any subsequent requests within the same session time scope.

Now, we will advance and learn the Java Servlet Response Phase.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Java Servlet Response

The second important part is the Response phase. The HttpResponse object is used to represent the HTTP response to your request. A web application sends back a response page to the user to respond to the HTTP request from the browser sent to your web application.

Let us now understand the parts of the Response Phase in the Java Servlets as follows.

  1. HTTP Response Header
  2. HTTP Response Content Type
  3. HTTP Response Content Length
  4. HTTP Response Write HTML
  5. HTTP Response Redirection 

1. HTTP Response Header

Similar to HTTP Request, the HTTP response includes headers. These are responsible for all the data written in the response.

2. HTTP Response Content Type

The Content-Type header tells the browser about the type of content you are sending in return.

3. HTTP Response Content-Length

The Content-Length header tells you about the number of bytes your Servlet is sending in return.

4. HTTP Response Write HTML

To send the HTML back to the browser, you need to retrieve the PrintWriter from the HTTP response object.

5. HTTP Response Redirection 

Redirecting will help you turn yourself to a different webpage from the current one.

With both the Request and Response phases discussed, we will dive into the practical mode where we learn to set up the environment for Java Servlets and execute a sample program for better understanding.

Environmental Setup

Open Windows and search for Environmental Variables

environment-setting-java-servlets-1

Select environmental variables

environment-setting-java-servlets-2

Select new and add the following as Home Variables

//Set up JAVA_HOME 

C:\Users\Honey\Downloads\jdk-14.0.1_windows-x64_bin.zip\jdk-14.0.1

environment-setting-java-servlets-java-home

(USE your local system file location)

//Set up JRE_HOME

C:\Program Files\Java\jre1.8.0_251 

environment-setting-java-servlets-JRE-home

(USE your local system file location)

//Set up CATLINA_HOME

C:\Program Files\Apache Software Foundation\Tomcat 8.5 

environment-setting-java-servlets-Catlina-home

(USE your local system file location)

Now get into Path Variables and add new path variables

environment-setting-java-servlets-3

//Set up JAVA_PATH

C:\Users\Honey\Downloads\jdk-14.0.1_windows-x64_bin.zip\jdk-14.0.1\bin 

environment-setting-java-servlets-Java-path

(USE your local system file location)

//Set up JRE_PATH

C:\Program Files\Java\jre1.8.0_251\bin 

environment-setting-java-servlets-JRE-path

(USE your local system file location)

//Set up CATLINA_PATH

C:\Program Files\Apache Software Foundation\Tomcat 8.5\bin 

environment-setting-java-servlets-tomcat-path

(USE your local system file location)

//Synchronize TOMCAT with Eclipse

After setting up the Home and Path variables, fire up the tomcat server and Eclipse. Then add the Tomcat server to your eclipse and start the server by right-clicking on the server in console.

java-servlets-start-Tomcat

// Port numbers Configured:

To configure the server, double click on it 

java-servlets-tomcat-server-settings

After it is started, you will find the following dialogue box.

setting-java-servlets-setup-ports

Edit the following numbers for Tomcat admin, AJP, and HTTP Ports.

// Tomcat Admin Port number: 8086

// HTTP Port: 8000

// AJP: 8008

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Java Servlet Example

package Servlet;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/SServlet")

public class SServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

     public SServlet() {

        // TODO Auto-generated constructor stub

    }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

/* TODO Auto-generated method stub

response.getWriter().append("Served at: ").append(request.getContextPath());*/

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.print("<html><body>");

out.print("<h2>Hello. Welcome to Simplilearn</h2>");

out.print("</body></html>");

}

}

Execute the program depicted above and you will receive the following output.

//Expected Output:

Hello. Welcome to Simplilearn

/output

Followed by the example, we enter the Java Servlet Session Tracking, Session Management, and Cookies.

Java Servlet Session Tracking

Servlet Session Tracking

Session Tracking is a simple procedure used to maintain various data types related to a specific user in servlets. The data may be search history, login credentials.

The following picture depicts the flow of Session Tracking in Java Servlets.

The requests sent by the user are recorded and saved to keep track of his activities on the website and browser he is currently surfing in.  

Java Servlet Cookies

Cookies

A cookie is a small piece of information that is persisted between multiple client requests. A cookie incorporates a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

The following picture depicts the cookie management in Java Servlets.

The user logins to the website and surfs through the Website. His activities and login credentials will be saved in the form of cookies to help him through easy login or provide him with his recent browsing details that may be considered as his favorites.

Moving ahead through our article, we will learn the top of the line advantages that Java Servlet provides and the reasons that give it an edge over other similar technologies. 

Java Servlet Advantages

The following are the significant Advantages of Java Servlets.

  • Servlets create dynamic documents that are easier to write and faster to run.
  • Servlets inherit the powerful features of JAVA, which include
  1. Exception handling
  2. Garbage collection
  3. Java Security
  • Java Servlets are highly portable and perform in Web Servers regardless of the platform.
  • Java Servlets can establish communication with different servlets and servers.

Followed by the advantages of servlets, we will now discuss the disadvantages of Servlets.

Java Servlet Disadvantages

The following are the disadvantages of the Java Servlets.

  • Designing Java Servlets is known to be complicated.
  • Java Servlets are heavy and sometimes slow down application performance.
  • Complex business logic turns the application challenging to decode.
  • It is mandatory to have JRE on the server-side to run servlets. 

So with that, we finish the Advantages and Disadvantages of Java Servlets. Moving ahead, we will go through a brief understanding of another similar technology to Java Servlets, the CGI (Computer Graphics Interface).

CGI

CGI stands for Common Gateway Interface. Like the Java Servlet, it designs the CGI to allow the webserver to call an external program, pass HTTP requests to the external program, and process it.

The following diagram depicts the fundamental architecture of CGI.

CGI

It distributes the HTTP Request received amongst the CGI shells, as shown in the diagram above. While in the Java Servlets, it distributes the request for processing amongst the threads.

Having said a few pointers about CGI and Servlets, it is the right time to discuss some significant differences between the Java Servlets and CGI.

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

CGI v/s Java Servlet

The following table of comparison gives the differences between a Java Servlet and CGI.

Java Servlets

CGI

Servlets are written and run in JVM

CGI Scripts are executable codes written in native OS

Performance is high

Performance is low

Platform independent

Hard to switch between platforms

It translates Servlets to byte-code

CGI scripts are directly executed

Servlets are portable

CGI is not portable

With this, we have come to the end of the Java Servlets Article. Java Servlets have proven to be a one-stop solution for designing, developing, deploying, and maintaining Web Services. We are now moving further. The next milestone you need to reach lies in mastering the APIs in Java.

Are You Looking for More In-Depth Knowledge About Java? 

Need information on how to get certified as a professional developer?

Explore our Java training and certification programs, which Simplilearn's experienced industry experts offer in real-time. In particular, check out our Full Stack Java Developer Master's Program today!

If you have any questions about this "Java Servlets" article, please leave them in the comments section, and our experts will get back to you on the same, immediately.

FAQs

1. Is servlet a framework?

No, a servlet is not a framework. Servlets are Java classes that handle HTTP requests and generate responses. They are part of the Java EE (Enterprise Edition) platform and provide a way to develop web applications in Java. Servlets are the backbone of Java web development and are often used in conjunction with frameworks like JavaServer Faces (JSF), Spring MVC, or Apache Struts to simplify web application development.

2. How to create a servlet in Java?

To create a servlet in Java, you need to follow these steps:

  1. Create a Java class that extends the javax.servlet.http.HttpServlet class.
  2. Override the doGet() or doPost() method to handle HTTP GET or POST requests, respectively.
  3. Implement the logic to process the request and generate a response.
  4. Compile the servlet class using a Java compiler.
  5. Deploy the compiled servlet class to a servlet container or application server, such as Apache Tomcat or Jetty.

3. Why do we use servlets in Java?

Servlets are used in Java for web development because they provide a server-side solution for handling HTTP requests and generating dynamic web content. Some reasons for using servlets in Java include:

  1. Platform Independence: Servlets are written in Java, making them platform-independent and allowing them to run on any Java-enabled server.
  2. Efficiency: Servlets are efficient in terms of memory usage and performance compared to other server-side technologies.
  3. Scalability: Servlets can handle multiple concurrent requests efficiently, making them suitable for high-traffic web applications.
  4. Integration: Servlets can be integrated with other Java technologies and frameworks to build complex web applications.
  5. Security: Servlets provide built-in security features, such as session management and authentication, to ensure the security of web applications.

4. What is a generic servlet in Java?

A generic servlet in Java is a class that implements the javax.servlet.Servlet interface. Unlike HTTP servlets, which are specifically designed to handle HTTP requests and responses, generic servlets are protocol-independent and can handle any type of request and response. Generic servlets provide a basic framework for building servlet-based applications and are often extended to create custom servlet classes.

5. What is the difference between servlet and JSP in Java?

Servlets and JavaServer Pages (JSP) are both Java technologies used for web development, but they serve different purposes and have different features:

  1. Servlets: Servlets are Java classes that handle HTTP requests and generate responses dynamically. They are the backbone of Java web development and provide a way to create server-side logic for web applications.
  2. JSP: JavaServer Pages are text-based documents that contain HTML or XML markup along with embedded Java code. JSP pages are compiled into servlets by the web container at runtime, making them easier to write and maintain than servlets for generating dynamic web content.

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.