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.
Table of Contents
In this post, we will dive deep into the concept of Servlet but first, we must understand the architecture of the web.
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.
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.
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.
Overall there are four stages during its lifecycle:
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.
To create a Servlet, the highlighting steps are:
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.
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.
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); } }
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.
Developing Java Servlets has many advantages some of which are:
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
Create a free profile and find your next great opportunity.
Sign up and find a perfect match for your team.
Xperti vets skilled professionals with its unique talent-matching process.
Connect and engage with technology enthusiasts.
© Xperti.io All Rights Reserved
Privacy
Terms of use