Blog
Introduction to Servlet – A Beginner Tutorial to Learn Servlets
- February 9, 2022
- Posted by: jcodebook
- Category: Servlet Tutorials
In this cutting-edge time of the web, billion bytes of data are produced every day over the web. To access this data, everyone is required to send a request over the web and wait for a response. The Web began to be used for delivering services and service providers recognized, there is a need for web applications that generate dynamic content based on clients/user requests. The Web application can be developed based on Java technology i.e. Java Servlets for generating dynamic content.
In this tutorial, you will understand the following topics
- What is the Web
- What is a Web Application
- What is HTTP
- Difference b/w Get and Post HTTP Methods
- What is Servlet
- What is CGI and Its Limitations
- Advantages of Servlet over CGI
- Working of Servlet
- Web Container/Servlet Container
- Features of Servlet
- Creating First Servlet Program
Before getting dive into the concepts of Java Servlet technology, let us understand the fundamentals of the Web.
What is the Web?
The World Wide Web (WWW), commonly known as the Web. It is a system of Internet servers that supports formatted documents which are formatted using a markup language called HTML (Hyper Text Markup Language) that supports links to other documents, like graphics, text, audio, and video files.
In the above Figure, the web client (web browser) makes requests to a web server. Then, the web server receives the request, finds the resources, and returns the response to the client.
What is a Web Application?
A web application is application software that runs on a web server and can be of two types:
- Static Website/Application
- Dynamic Website/Application
Static websites are very basic websites and easy to create. You don’t need the knowledge of web programming and database design to create a static website. Its web pages are coded in Hyper Text Markup Language (HTML).
The page will remain the same for all users until someone changes it manually, so the information contained in the web page does not change and it looks like a printed page.
A dynamic website is a collection of dynamic web pages whose content changes dynamically. It accesses content from a database, therefore, when you alter or update the content of the database, the content of the website is also altered or updated.
A Web application with dynamic functionality on the server like Google, Facebook, Twitter, and many more are examples of web applications.
Therefore, the main difference between static and dynamic web pages is that the content of static pages remains the same for all the users however the content of dynamic web pages changes based on the request from a client (user’s browser).
Documents or resources on the Web are transferred via the Hypertext Transfer Protocol (HTTP), accessed by users by a software application called a web browser, and are published by a software application called a web server.
HTTP (Hypertext Transfer Protocol)
- HTTP is a communication protocol used between clients and servers on the Web.
- HTTP is a stateless protocol i.e. doesn’t maintain the state of a user and supports only one request per connection. This means that the clients connect to the HTTP server to send only one request and then disconnect.
- The HTTP request can be made using a variety of methods, but the ones which we use widely are Get and Post.
GET method is designed for getting information (a document, a chart, or the results from a database query), while the POST method is designed for posting information (a credit card number, some new chart data, or information that is to be stored in a database).
Get Method
- In the Get method, the information is passed as a sequence of characters appended to the request URL known as a query string. Therefore, the information sent by the client using the Get method is not secure as it is visible on the URL.
- Placing the extra information in the URL in this way allows the page to be bookmarked or emailed.
- We can’t send a large amount of information, some server limits the length of URL and query strings to about 240 characters.
Post Method
- Post request passes all its data, of unlimited length, directly over the socket connection as part of its HTTP request body.
- Consequently, POST requests cannot be bookmarked or emailed.
- It is secure then Get method as information sent to the server is not appended on URL and should be sent only once.
Now, that you have learned a few basics of web and web applications, let’s jump to the core topic and understand the concept of a Servlet.
What is Servlet?
Servlets are server-side programs written in Java that generates dynamic web content and are executed on a web server.
A Servlet is a Java-based web component, managed by a web container that generates dynamic content. Like other Java technology-based components, servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.
The following Figure illustrates the interaction between a web client and a web application that uses a servlet.
In the above picture, the client sends an HTTP request to the webserver. A web server that implements Java Servlet and Java Server Pages technology converts the request into an HttpServletRequest object. This object is delivered to a web component, which can interact with JavaBeans components or a database to generate dynamic content. The web component can then generate an HttpServletResponse or can pass the request to another web component. A web component eventually generates a HttpServletResponse object. The web server converts this object to an HTTP response and returns it to the client
So, before diving into the concept of Servlet, let’s see what technology was used before servlet?
Common Gateway Interface(CGI)
Initially, Common Gateway Interface (CGI) server-side scripts were the main technology used to generate dynamic content. CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response. A variety of different languages were used to build CGI programs. These included C, C++, and Perl.
But why did we stop CGI and moved to Servlet Technology? Let’s first understand the limitations of CGI over Servlets.
Limitations of CGI
However, CGI suffered serious performance problems. It was expensive in terms of processor and memory resources to create a separate process for each client request.
It was also expensive to open and close database connections for each client request. In addition, the CGI programs were not platform-independent. Therefore, other techniques like Servlets were introduced.
Although widely used, CGI scripting technology had many shortcomings, including performance, platform dependence, and lack of scalability. To address these limitations, Java Servlet technology was created as a portable way to provide dynamic, user-oriented content.
Note: CGI defines the interface between Web servers and Programs, No supporting infrastructure i.e. (Security, Sessions management, Instance persistence, etc.). It is Inefficient (i.e. creates a new process/script for each request!!!).
Advantages of Servlet over CGI
Servlets offer several advantages in comparison with CGI.
First, the performance of the servlet is significantly better than CGI. In servlet, no separate process is created to handle multiple client requests i.e. one servlet instance for multiple requests.
For example, If 1000 clients are accessing the web application, then the server has to create 1000 CGI processes/scripts to handle the request. Since Servlet doesn’t create a new process every time for a new request i.e. Servlets loaded only once in memory space.
Second, servlets are platform-independent because they are written in Java.
Third, the Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. It means servlets are more secure.
Finally, the full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.
Let’s understand the differences between CGI and Servlet with the help of the below table:
S.N | Common Gateway Interface(CGI) | Servlet |
---|---|---|
1. | Programs are written in the native OS like C, C++, and Perl. | Programs are written using Java language. |
2. | Platform dependent | Platform Independent |
3. | A new process is created for each client request. | No new process is created for each client. i.e. Servlet loaded only once. |
4. | Present in the form of executables (native to the server OS). | Compiled to Java Bytecode. |
5. | Not Scalable | Scalable |
6. | CGI scripts were slow. | Servlet are mush faster. |
7. | Less secure | More secure |
8. | Scripts are not portable | Servlets are portable. |
Note: Servlets loaded only “once”!! No new process is created for each client request. Servlet programs are more secure, scalable, and platform-independent. Therefore, the servlet came into the picture for the creation of dynamic content.
Let’s understand the working of Servlet.
Working of Servlet
Let us understand the working of the servlet with the help of the following typical sequence of events:
- A client (e.g., a Web browser) accesses a web application server and makes an HTTP request.
- The request is received by the web application server and handed off to the web container/servlet container.
- The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.
- The servlet uses the request object to find out the remote user, HTTP Post parameters that have been sent as part of this request, and other relevant data. The servlet process the request and generates data to send back to the client using the response object.
- Once the servlet has finished processing the request, the servlet container ensures that the response is properly flushed, and returns control back to the host Web server.
Web Container/ Servlet Container
A Web Container (also known as a servlet container) is the component of a web server that interacts with Java servlets. A Web container provides the runtime environment for running a servlet and manages various components of a Web application, such as HTML pages and servlets. Web containers provide various services required by Web applications, such as:
- Managing various stages in the life cycle of a servlet, such as initializing a servlet instance, processing the client request, and removing the servlet instance from the service.
- Defining the security constraints that specify that only authorized users can access the deployed servlets.
- Managing database transactions when a servlet needs to read and write data from a database, such as Oracle, MySQL, and SQL Server.
- Creating and removing servlet instances from an instance pool to serve multiple requests.
Note: Servlets don’t have a main() method. Web Container manages the life cycle of a Servlet instance.
Features of Servlet
Besides inheriting all the features of Java, servlets have the following features:
Portable
Since java is platform-independent, the same holds for servlets. For example, you can create a servlet on Windows operating system and later run it on any other operating system like Unix, Linux with Apache tomcat web server, this feature makes the servlet portable and this is the main advantage of servlet has over CGI.
Efficient and Scalable
Once a servlet is deployed and loaded on a web server, it can handle multiple client requests at the same time using the multithreading feature of Java. Compared to CGI where the server has to initiate a new process for every client request, the servlet is truly efficient and scalable.
Robust
By inheriting the top features of Java (such as Garbage collection, Exception handling, Java Security Manager, etc.) the servlet is less prone to memory management issues and memory leaks. This makes the development of web applications in servlets secure and less error-prone.
Secure
A Web container provides a runtime environment for executing a servlet. Servlets inherit the security feature provided by the Web container. This allows developers to focus on the servlet functionality and leave the security issues to the Web container to handle.
Session Management
It is the mechanism of tracking the state of a user across multiple requests. A session maintains the user’s identity and state across multiple requests.
Instance Persistence
Servlets help to enhance the performance of the server by preventing frequent disk access. For example, if a customer logs on to an online banking site, the customer can perform activities such as checking for the balance or applying for a loan. The account number of the customer will be validated at every stage from the database. Instead of checking the account number every time against the database, servlets retain the account number in the memory till the user logs out of the Web site.
Creating First Servlet Program
The following is the first Servlet program to display a simple text “Hello World”
HelloServlet.java
//Program to print "Hello World"
package jcodebook;
import java.io. *;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Hello World");
}
}
Output
Hello World
package jcodebook;
It is a simple package name for the Servlet class.
import java.io.*;
java.io package is needed for PrintWriter, IOException, and I/O operations.
import javax.servlet.*;
This package contains the classes and interfaces required to build servlets. You will learn more about these later in this tutorial.
public class HelloServlet extends GenericServlet
Next, the program defines HelloServlet as a subclass of GenericServlet. To write a servlet, it is required to extend the abstract class GenericServlet, like Applet is required to extend to write an Applet.
A GenericServlet class is defined in javax.servlet package and is a protocol-independent Servlet that means it can handle any type of request (Generic, HTTP) and it always overrides the service() method to handle the client request/response.
public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException
Inside HelloServlet, the service( ) method (which is inherited from GenericServlet) is overridden. This method handles client requests using the object of ServletRequest interface that is defined as a first argument in service( ) method. The second argument is a ServletResponse object that enables the servlet to formulate a response for the client.
The service() method throws two checked exceptions i.e. javax.servlet.ServletException and java.io.IOException.
response.setContentType(“text/html”);
The setContentType(String str) method is defined in the ServletResponse interface and takes a string parameter and does not return anything (returns void).
setContentType() method establishes the MIME(Multipurpose Internet Mail Extension) type of the HTTP response. The data that can be sent may be simple plain text, HTML form, XML form, image form of type gif or jpg, excel sheet, etc.
In this program, the MIME-type is “text/html”. This indicates that the browser should interpret the content as HTML source code.
Example:
response.setContentType(“text/html”);
In “text/html”, “text” is known as type and “html” known as subtype. A type contains many subtypes.
List of Content Types
- text/html
- text/plain
- application/msword
- application/vnd.ms-excel etc.
PrintWriter pw = response.getWriter();
Next, getWriter() method defined in ServletResponse interface and return an object of PrintWriter. Anything written to this stream is sent to the client as part of the HTTP response.
pw.println(“Hello World”);
Then println() is defined in PrintWriter class and is used to write some simple HTML text as the HTTP response. This string message (here, “Hello, World”) is ultimately sent to the client as a response by the ServletResponse.
So, that was the small introduction of Servlet. I hope you enjoyed this blog and definitely, it helps to improve your existing knowledge.
Happy Learning !!!
Quick Links
How to Install Eclipse IDE and Configure Apache Tomcat Server to write Servlet Applications?
Creating First Servlet Project in Eclipse IDE- A Step by Step Guide