Updated April 7, 2023
Introduction to Servlet in Java
Servlet in Java can be described in many ways. As a technology, the servlet is used to create web pages; as an API, which provides interfaces, etc. It is used to extend the capabilities of the server which hosts applications on a request-response programming model. Servlets provide component-based and a platform-independent method to build web-based applications without any performance limitations. Servlets in Java have entire access over Java API’s and JDBC to access the enterprise database. We shall see in detail what are these Servlets, why are they used, its advantages and limitations, and how actually servlets work in Java.
Servlets can be described in many other ways,
- Servlet is a technology that is being used to create web applications
- Servlet is also an API that provides many interfaces and classes along with documentation
- It is an interface that is implemented for creating Servlet in Java
- It is a class that extends the capabilities of the server and responds to incoming requests. It can be any type of request.
- It is also a web component deployed on the server to create dynamic web pages.
Why do we need Servlet in Java?
With growing technology, we need to get ourselves acquainted with the latest updates or latest tech stack daily. Servlets act as an interface, or as a technology, or as a web component, or a class, or as an API. With servlets, we can collect user information through web pages/ forms, or a database, and any other data sources and create web pages.
- Servlets in Java is similar to programs implemented using Common Gateway Interface(CGI), but Servlets have additional advantages over CGI.
- Performance-wise, servlets are significantly better than CGI.
- Are platform-independent as the servlets are written in Java.
- They execute within the space of Web server. We need not create a separate process in handling a client request.
- Java Security enforces a strict set of restrictions in protecting the resources of a server machine, and hence Servlet is trusted.
- Servlets can communicate with databases, applets, or some other software via sockets, RMI mechanisms.
How does Servlet Work in Java?
Servlets in Java check the communication interface, requirements of client and server, the protocol used, programming language, and the software involved. Servlets get executed in the following steps,
Step 1: The client sends a request to the web server, reads explicit data sent by the client, which can be HTML form, applet, or custom HTTP client program.
Step 2: The web server then receives the request.
Step 3: The web server then passes the request to the corresponding servlet, the processing request may include communicating with the database, invoking web service, or direct response.
Step 4: Servlet then processes the request and generates a response in the form of output. It can be in any format, HTML or XML, GIF if images, or Excel.
Step 5: These servlets then sends a response back to the server
Step 6: Then the web server sends a response back to the client and the client, as the browser display on the UI.
Servlet Architecture
The above servlet architecture uses some Java methods like:
- Servlet.init(): Called by Servlet to indicate Servlet instance is executed successfully and service is invoked. Servlet then calls service() method to process client’s request. Then terminated once service is done by using destroy() method
- Servlet.destroy(): method will run only once during the entire lifecycle which gives us a signal that it is the end of the Servlet instance.
Examples to create Servlet in Java
First, we need to install Java, Eclipse, and Tomcat:
1. We will create a Dynamic Web project using File-> New-> Dynamic Web Project.
2. Enter Project Name and select Target Runtime, Clicking on Next, need to check mark “Generate web.xml” and then Finish
3. The project structure will look somewhat as below.
4. Then, Click on File-> Create New Servlet.
5. Click on Finish above. Now Eclipse will generate Servlet Class based on the inputs or configuration done in previous steps.
Code:
FirstProgram.java
package com.srccode.example;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FirstProgram
*/
@WebServlet("/FirstProgram")
public class FirstProgram extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FirstProgram() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
We shall modify our code for Servlet Class as below,
package com.srccode.example;
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;
/**
* Servlet implementation class FirstProgram
*/
@WebServlet("/FirstProgram")
public class FirstProgram extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FirstProgram() {
super();
// TODO Auto-generated constructor stub
}
private String mymsg;
public void init() throws ServletException {
mymsg = "Hi eduCBA Team! We are working on Java Servlet Tutorial! This is the first Servlet Program!";
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
printWriter.println("<h1>" + mymsg + "</h1>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
In web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ServletExample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
In index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BeginnersBook Servlet Demo</title>
</head>
<body>
<a href="welcome">Click to call Servlet</a>
</body>
</html>
Output:
Right, Click on the Project and Select Run As-> Run on Server.
Now Open the Browser and we can see the below Output, server will run on localhost:<port no.>
http://localhost:8080/ServletExample/FirstProgram
Advantages of Servlet in Java
There are many advantages of Servlet in Java. Servlets can be taken as applet running on the server-side:
- Servlets are persistent: The Servlet remains inside memory until they are destroyed with destroy() method, which helps in serving the incoming request. It establishes connection only once with Database and can handle many requests on the same database. Reduced time and resources used to connect to the Database or any other source
- Servlets are portable: which means, servlets are compatible with all Operating systems i.e. programs written in one Operating System can be executed on other Operating System
- Servlets are Independent of Server: Servlets are compatible with any web server available in the market
- Servlets are Protocol Independent: Servlets can support any protocols like FTP, Telnet, etc. It provides extended support for HTTP protocol
- Servlets are Secure: Since these Servlets are server-side programs and are invoked by the web server alone, all security measures taken by the web server are inherited
- Servlets are Extensible: Servlets can be extended and polymorphed into objects based on users requirement
- Servlets are Fast: Since these servlets are compiled into bytecodes, execute more quickly compared to other scripting languages. And also provides type checking and strong error.
- Servlets are inexpensive: There are many free web servers available for any type of use, may it be personal or commercial.
With this, we conclude the topic ‘Servlet in Java’. We have seen what Servlets are in Java and How are they used with an example. We have also seen its advantages and learned how Servlets can be used step by step with Servlet Architecture and Servlet methods used. Also seen Why Servlets are used in Java and its advantages over CGI. We have much more to explore on Servlets, there are types of Servlets also available, will dig deeper in further tutorials.
Recommended Articles
This is a guide to Servlet in Java. Here we discuss the basic concept, Advantages, why do we need Servlet in Java, and how does it works along with Examples and Code Implementation. You can also go through our other suggested articles to learn more –