What Is Servlet And Where To Use It Effectively

May 27, 2022
What Is Servlet and Where to Use It Effectively



Introduction

Being an internet user, we know that on daily basis petabytes of data move through the internet servers which is requested by billions of devices around the world. Most of it comes from the users who are using different gadgets like smartphones, tablets, laptops, IoT devices, etc. In most cases, users are surfing the internet for information that is being rendered on their devices as web pages. These web pages are developed through programming languages like PHP, ASP.Net, Javascript, Python, and Java. If we talk specifically about Java, then the services that bring this data are developed using Servlets.

new java job roles

In this post, we will dive deep into the concept of Servlet but first, we must understand the architecture of the web.

Web Architecture

The web is a setup of connected servers that serve documents of specific formats though they are hosted differently. The documents or pages shown to end-users are formatted using a markup language called HTML (HyperText Markup Language) that supports links to other documents/pages, like videos, audios, pictures, animations, etc.

If we take an example of Facebook we can see different sections like Posts, Short Reels, and Stories all of which are actually small pages embedded within a larger frame called a website. On every website, there are two methods through which we manipulate the data. These are GET and POST. GET is used to fetch the data from internet servers and displays it on an HTML page while the POST puts your data on the internet e.g. creating a Facebook post, story, or short reel.

What are Java Servlets?

Java Servlets are used to create web applications that create dynamic web pages rather than static ones. This technology is robust and scalable since it is backed by the Java language and runs on a Java-enabled web server or application server. They are used to intercept the request fetched from the web server, process the request, produce the response as per the code block or algorithm, and send a response back to the webserver.

What is a Servlet in Java, technically?

In technical terms, a servlet is a Java class used to broaden the capabilities of servers that host applications accessed by means of a request-response programming model. Java Servlets can respond to any type of request and are commonly used to extend the applications hosted by web servers and are defined by HTTP-specific servlet classes.

Two packages play a pivotal role in this aspect, one is javax.servlet and the second one is javax.servlet.http. These packages provide interfaces and classes for writing servlets. As per the rule, servlets must implement the Servlet interface that defines lifecycle methods. Along with this, one thing to note is that for implementing a generic service, we can use or extend the GenericServlet class provided with the Java Servlet API. The class, HttpServlet exposes methods, such as doGet and doPost to handle HTTP-specific services.

Servlet Lifecycle

Overall there are four stages during its lifecycle:

  1. Loading Servlet:- Loads the servlet class e.g. loading on a web server that is running Apache Tomcat.
  2. Initializing Servlet:- Initializes the servlet instance by calling the init method
  3. Handling request:- Invokes the service method, passing request and response objects.
  4. Destroying Servlet:- If it needs to remove the servlet, the container finalizes the servlet by calling the servlet’s destroy method.

init and destroy methods are called only once. Once out of scope, a servlet is garbage collected by the garbage collector of the Java virtual machine famously known as JVM.

How to create Java Servlets

To create a Servlet, the highlighting steps are:

  1. Create a Servlet
  2. Compile the Servlet
  3. Add mappings to the web.xml file
  4. Start the server and deploy the project
  5. Access the servlet

Let’s expand on the above points.

To run a servlet program, a prerequisite is to have Apache Tomcat Server installed and configured. Do note that for any Servlet program, you will need 3 files – index.html file, Java class file, and web.xml file.

Let’s perform a small exercise in which we will multiply two numbers using Servlets and displays the output in a browser.

Step # 1:

Create an index.html file. Within this file write the following:

<!DOCTYPE HTML>
<html>
<body>
 <form action = "multiply">

  Enter 1st number: <input type="text" name ="num1">

  Enter 2nd number: <input type="text" name="num2">

 </form>

 </body>
</html>

The above code creates a form to enter the numbers for the multiplication operation.

Step # 2:

Let’s now create a Java class file that will perform the operation.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Multiply extends HttpServlet{

public void service(HttpServletRequest req, HttpServletResponse res) throws IOException
  {
    int a = Integer.parseInt(req.getParameter("num1"));
    int b = Integer.parseInt(req.getParameter("num2"));
    int result = a*b;
    PrintWriter out = res.getWriter();
    out.println("Result:- " + result);
  }
}

Step # 3:

And the last step is to add mappings to the web.xml file. The web.xml file will be present in the WEB-INF folder of the web content.

Once the web.xml file is ready, add the following mappings to it:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns_xsi="<a href=" http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>" 
http://java.sun.com/xml/ns/javaee">http://java.sun.com/xml/ns/javaee</a>" xsi_schemaLocation="<a href="http://java.sun.com/xml/ns/javaee">
http://java.sun.com/xml/ns/javaee</a> <a href="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd</a>" version="3.0">
  <display-name>Basic</display-name>
  <servlet>
    <servlet-name>Multiplication</servlet-name>
    <servlet-class>waqas.Multiply</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Multiplication</servlet-name>
    <url-pattern>/multiply</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>

Once the above steps are done, we can execute the program by starting the webserver and getting the desired output on the browser.

Advantages of Servlet

Developing Java Servlets has many advantages some of which are:

  1. Portability:- It uses Java language which is machine-independent.
  2. Performance:- It creates a thread for each request, not a process that makes it better.
  3. Robust:- Java virtual machine manages Servlets, which handles memory leaks, garbage collection, etc.
  4. Secure:- It uses Java language which is in principle secure.

Conclusion

We have seen in this post that Servlets in Java provide a robust and secure way of displaying and posting the data through web pages. To use it effectively by Java developers one has to excel in understanding the underlying concepts and implement pet projects to get a thorough understanding of Servlet so that he can utilize it in his client-specific projects.

Also Read: How to use Java Generic Interface

new Java jobs



author

admin


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US