Introduction to Java Servlets — Servlets in a Nutshell

Swatee Chand
Edureka
Published in
12 min readDec 12, 2018

--

Introduction To Java Servlets - Edureka

In this modern era of the internet, billion bytes of data is generated on a day-to-day basis. To gain access to this humongous amount of data, every person is required to send a request on the network and await a response. Most of us believe in the misconception that all of these web applications are created over web frameworks like HTML, PHP, JavaScript etc. But, did you know, web applications can be based on Java using a service called Java Servlets? In this article, let’s delve deep into Java Servlets and understand how this technology is useful for creating a web application.

Below is the list of topics that I will be covering in this Java Servlets tutorial:

  • Introduction to Web
  • Web & HTTP
  • Introduction to Servlet
  • Servlet Architecture
  • Steps to Create Servlet
  • Generic Servlet
  • Servlet Classes & Interfaces

Before we jump into servlets, let’s understand a few fundamentals of Web.

Introduction to Web

Web is basically a system of Internet servers that supports formatted documents. The documents are formatted using a markup language called HTML (HyperText Markup Language) that supports links to other documents, like graphics, audio, and video files.

Web consists of billions of clients and servers connected through wires and wireless networks. First, web clients make requests to a web server. Then, the web server receives the request, finds the resources and returns the response to the client. When a server answers a request, it usually sends some type of content to the client. Then, the client uses a web browser to send a request to the server. The server often sends a response back to the browser with a set of instructions written in HTML. All browsers know how to display HTML pages to the client.

Basically, this is all about the backend working of the WWW (World Wide Web). Now, let’s understand the connectivity between Web & HTTP.

Web & HTTP

A website is a collection of static files i.e. web pages such as HTML pages, images, graphics etc. A Web application is a website with dynamic functionality on the server. Google, Facebook, Twitter are examples of web applications.

So, what is the link between the Web and HTTP? Let’s now find out.

HTTP (Hypertext Transfer Protocol)

  • HTTP is a protocol that clients and servers on the web to communicate.
  • It is similar to other internet protocols such as SMTP (Simple Mail Transfer Protocol) and FTP (File Transfer Protocol.
  • HTTP is a stateless protocol i.e it supports only one request per connection. This means that with HTTP the clients connect to the server to send one request and then disconnect. This mechanism allows more users to connect to a given server over a period of time.
  • The client sends an HTTP request and the server answers with an HTML page to the client, using HTTP.

The HTTP request can be made using a variety of methods, but the ones which we use widely are Get and Post. The method name itself tells the server the kind of request that is being made, and how the rest of the message will be formatted.

Now, with the help of the below table, let’s understand the difference between Get and Post methods of HTTP.

Now, that you have learned a few basics of web, let’s jump to the core topic and understand the concept of a servlet.

Java Servlets: Introduction to Servlets

A servlet is a Java Programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. It is also a web component that is deployed on the server to create a dynamic web page.

In this figure you can see, a client sends a request to the server and the server generates the response, analyses it and sends the response to the client.

So, before we jump into the depth of Servlets, let’s see the technology that was used before servlets came into the picture.

CGI vs Servlets

Before servlets, we had CGI i.e. Common Gateway Interface. It is a standard way for a Web server to pass a user’s request to an application program and receives the response to forward to the user. When the user requests a Web page, the server sends back the requested page. However, when a user fills out a form on a Web page and sends it in, it is processed by an application program. The Web server typically passes the form information to a small application program. This program processes the data and sends back a confirmation message. This process of passing data back and forth between the server and the application is called the common gateway interface (CGI). It is part of the Web’s Hypertext Transfer Protocol.

But, why did we stopped using it and switched to servlets? Let’s understand this with the help of the below table:

I hope that based on the above comparison, one can conclude, why Servlets are being used for Web Applications. Now, let’s move ahead with this article and understand Servlet Architecture.

Servlet Architecture

The architecture, here, discusses the communication interface, protocol used, requirements of client and server, the programming with the languages and software involved. Basically, it performs the below-mentioned tasks.

  • First, it reads the explicit data sent by the clients (browsers). This data can include an HTML form on a Web page, an applet or a custom HTTP client program. It also reads implicit HTTP request data sent by the clients (browsers). This can include cookies, media types and compression schemes the browser understands, and so forth.
  • After that, the servlet processes the data and generate the results. This process may require communicating to a database, executing an RMI, invoking a Web service, or computing the response directly.
  • After processing, it sends the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), or Excel formats.
  • Finally, it also sends the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned.

Now, let’s understand the various methods in the life cycle of a servlet.

Servlet Life Cycle

The Servlet life cycle mainly includes the following four stages,

  • Loading a Servlet
  • Initializing the Servlet
  • Request handling
  • Destroying the Servlet
  1. When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all the servlets.
  2. The servlet is initialized by calling the init() method. The Servlet.init() method is called by the Servlet container to indicate that this Servlet instance is instantiated successfully and is about to put into service.
  3. The servlet then calls service() method to process a client’s request. This method is invoked to inform the Servlet about the client requests.
  4. The servlet is terminated by calling the destroy().
  5. The destroy() method runs only once during the lifetime of a Servlet and signals the end of the Servlet instance.

init() and destroy() methods are called only once. Finally, a servlet is garbage collected by the garbage collector of the JVM. So this concludes the life cycle of a servlet. Now, let me guide you through the steps of creating java servlets.

Steps to Create Servlet

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

Now, based on the above steps, let’s write a program and understand how a servlet works.

To run a servlet program, we should have Apache Tomcat Server installed and configured. Eclipse for Java EE provides in-built Apache Tomcat. Once the server is configured, you can start with your program. One important point to note — for any servlet program, you need 3 files — index.html file, Java class file, and web.xml file. The very first step is to create a Dynamic Web Project and then proceed further.

Now, let’s see how to add 2 numbers using servlets and display the output in the browser.

First, I will write index.html file

<!DOCTYPE HTML> 
<html>
<body>

<form action = "add">
Enter 1st number: <input type="text" name ="num1">
Enter 2nd number: <input type="text" name="num2">
</form>

</body>
</html>

Above program creates a form to enter the numbers for the addition operation. Without the Java class file, you can’t perform addition on 2 numbers. So let’s now create a class file.

package edureka;
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 Add extends HttpServlet{
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException
{
int i = Integer.parseInt(req.getParameter("num1"));
int j = Integer.parseInt(req.getParameter("num2"));
int k= i+j;
PrintWriter out = res.getWriter();
out.println("Result is"+k);
}
}

After writing the Java class file, the last step is to add mappings to the web.xml file. Let’s see how to do that.

The web.xml file will be present in the WEB-INF folder of your web content. If it is not present, then you can click on Deployment Descriptor and click on Generate Deployment Descriptor Stub. Once you get your web.xml file ready, you need to add the mappings to it. Let’s see how mapping is done using the below example:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>Basic</display-name>
<servlet>
<servlet-name>Addition</servlet-name>
<servlet-class>edureka.Add</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Addition</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Once done, you can execute the program by starting the server and get the desired output on the browser.

Let’s take another example where I will be creating a simple login servlet. Again, the very first step will be to write html file.

<!DOCTYPE html>
<html>
<body>
<form action="Login" method="post">
<table>
<tr>
<td><font face="verdana" size="2px">Name:</font></td>
<td><input type="text" name="userName"></td>
</tr>
<tr>
<td><font face="verdana" size="2px">Password:</font></td>
<td><input type="password" name="userPassword"></td>
</tr>
</table>
<input type="submit" value="Login">
</form>
</body>
</html>

Next, let’s code the Java Class file.

package Edureka;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Login extends HttpServlet
{
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
PrintWriter pw=res.getWriter();
res.setContentType("text/html");
String user=req.getParameter("userName");
String pass=req.getParameter("userPassword");
pw.println("Login Success...!");
if(user.equals("edureka") && pass.equals("edureka"))
pw.println("Login Success...!");
else
pw.println("Login Failed...!");
pw.close();
}
}

In the above code, I have set a condition — if username and password are both equal to edureka, only then it will display successfully logged in, else login will be denied.

Let’s add the mappings to the web.xml file now.

<?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"version="3.1">
<display-name>LoginServlet</display-name>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Edureka.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

So, this is how a servlet is created and configured. Let’s now see what a Generic servlet is and how is it created.

Generic Servlets

A Generic servlet is a protocol-independent servlet that should always override the service() method to handle the client request. The service() method accepts two arguments, ServletRequest object, and ServletResponse object. The request object tells the servlet about the request made by the client while the response object is used to return a response back to the client. GenericServlet is an abstract class and it has only one abstract method, which is service(). That’s why when we create a Generic Servlet by extending the GenericServlet class, we must override the service() method.

Now, let’s see how to create and invoke a Generic servlet. Again I will code 3 files as shown below:

1. HTML file

We are creating an HTML file that will call the servlet once we click on the link on the web page. Create this file in the WebContent folder. The path of this file should look like this: WebContent/index.html

<html>
<title>Generic Servlet Demo</title>
</head>
<body>
<a href="welcome">Click here to call Generic Servlet</a>
</body>
</html>

2. Java Class file

Here we will be creating a Generic Servlet by extending GenericServlet class. When creating a GenericServlet, you must override the service() method. Right click on the src folder and create a new class file and name the file as generic. The file path should look like this: Java Resouces/src/default package/generic.java

package EdurekaGeneric;
import java.io.*;
importjavax.servlet.*;
public class generic extends GenericServlet{
public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter pwriter=res.getWriter();
pwriter.print("<html>");
pwriter.print("<body>");
pwriter.print("
<h2>Generic Servlet Example</h2>

");
pwriter.print("Welcome to Edureka YouTube Channel");
pwriter.print("</body>");
pwriter.print("</html>");
}
}

3. web.xml
This file can be found at this path WebContent/WEB-INF/web.xml. In this file we will map the Servlet with the specific URL. Since we are calling the welcome page upon clicking the link on index.html, it will map the welcome page to the Servlet class that we have already created above.

<?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/"version="3.1"/>
<display-name>LoginServlet</display-name>
<servlet>
<servlet-name>MyGenericServlet</servlet-name>
<servlet-class>EdurekaGeneric.generic</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyGenericServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

After this, start your Tomcat Server and run the servlet. You will get the desired output.
Now, let’s jump into the last section of this article, and see useful classes and interfaces of Java servlets.

Servlet Classes & Interfaces

Servlet API consists of two important packages that encapsulate all the important classes and interfaces, namely:

  • javax.servlet
  • javax.servlet.http

With the help of below table let’s see some important classes and Interfaces of a servlet.

This brings us to the end of our blog on Introduction to Java Servlets. I hope you found this blog informative and added value to your knowledge.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Java.

1. Object Oriented Programming

2. Inheritance in Java

3. Polymorphism in Java

4. Abstraction in Java

5. Java String

6. Java Array

7. Java Collections

8. Java Threads

9. Java Tutorial

10. Servlet and JSP Tutorial

11. Exception Handling in Java

12. Advanced Java Tutorial

13. Java Interview Questions

14. Java Programs

15. Kotlin vs Java

16. Dependency Injection Using Spring Boot

17. Comparable in Java

18. Top 10 Java frameworks

19. Java Reflection API

20. Top 30 Patterns in Java

21. Core Java Cheat Sheet

22. Socket Programming In Java

23. Java OOP Cheat Sheet

24. Annotations in Java

25. Library Management System Project in Java

26. Trees in Java

27. Machine Learning in Java

28. Top Data Structures & Algorithms in Java

29. Java Developer Skills

30. Top 55 Servlet Interview Questions

31. Top Java Projects

32. Java Strings Cheat Sheet

33. Nested Class in Java

34. Java Collections Interview Questions and Answers

35. How to Handle Deadlock in Java?

36. Top 50 Java Collections Interview Questions You Need to Know

37. What is the concept of String Pool in Java?

38. What is the difference between C, C++, and Java?

39. Palindrome in Java- How to check a number or string?

40. Top MVC Interview Questions and Answers You Need to Know

41. Top 10 Applications of Java Programming Language

42. Deadlock in Java

43. Square and Square Root in Java

44. Typecasting in Java

45. Operators in Java and its Types

46. Destructor in Java

47. Binary Search in Java

48. MVC Architecture in Java

49. Hibernate Interview Questions And Answers

Originally published at www.edureka.co on December 12, 2018.

--

--