A Brief Introduction To Servlets in Java


This article provides a brief introduction to servlets in Java. The Netbeans IDE is used for the example. We describe the following terms related to servlets, why we need servlets, what CGI is, how to establish communication between a server and a client, the differences between doGet() and doPost() methods, etcetera.

What is servlet

Servlet is a class to extend the properties of a server, It is used to design web-based applications. It is an Application Programming Interface (API) containing predefined interfaces and helper classes. Implementation of some of the interface is provided by application developers and the implementation of the rest of the interface is provided by the server vendor.

Why we need servlets

Before servlets there was another API called Common Gateway Interface (CGI) for developing web-based applications. Let's have a look at CGI.

What Common Gateway Interface (CGI) is

It is a protocol that was developed to facilitate communication between web server and a request processing program. In CGI based web applications the request process program was developed in C/C++ or Perl. The programs are called CGI scripts.


1.0: The client sends a request for some dynamic content to the server.

1.1: On receiving the request a process is submitted by the server to create a GUI and a Script.

1.2: The request is process by a CGI script and dynamic generated contents are provided to the server.

1.3: Dynamically generated content is sent as a response by the server.

CGI based applications have the following drawbacks:

  1. Execution of CGI scripts are process-based. Process-based execution creates more overhead and limits the scalability.
  2. CGI scripts were platform-dependent.

In that context and due to those drawbacks, a new technology is required; in other words servlets.


Technology that eliminates both of those drawbacks as in the following:

  1. The first drawback is removed by providing a thread-based processing model.
  2. The second drawback is removed by facilitating the development by request processing programs in Java.

Now understand servlets

javax.servlet.*; and its sub-packages contains classes and interfaces of the servlet API.

At the core of the servlet API is an interface name "Servlet" as in the javax.servlet.Servlet package. This interface provides servlet life cycle methods. Implementation of its needs are provided by all servlets.

It has the following method:

  • public void init(setConfig config);

This method is invoked only once just after a servlet object is created.

It  is used by the server to provide a refrence of the servlet configuration object to the servlet. The Servlet config is an interface of the servlet API. Implementation of it is provided by the servlet vendor.

  • public void service(SentRequest req, SentResponse res)throws ServletException, IOException;

          This method is invoked by the server each time a request is received for the servlet.

          This method is used by the servlet for processing a request. In this method a reference of an object is type ServletRequest and ServletResponses are provided by the server. This objects facilitates transfer of input between servlet and server.

  • public void destroy();

          This method is invoked only once just before a servlet is unloaded.

  • public ServletConfig getServletConfig();

          Used to obtain the reference of the ServletConfig object from the servlet.

  • public String getServletInfo();

          Used to obtain the description of the servlet.

Servlet Implementation

In order to define a servlet implementation of a Servlet, an interface must be provided.

To facilitate indirect implementation of the Servlet interface, Sun Microsystems provides a helper class named GenericServlet. It is an abstract class. It implements servlet interface and provides implementation of all its methods except service().


//implementation of Servlet through GenericServlet
public class MyServlet extends Generic Servlet
  //service() method is defined

How we create a connection between client and server

Communication between the client and server is done by the HTTP protocol. This protocol supports the following requests:

  1. Get
  2. Post
  3. Head
  4. Put
  5. Delete
  6. Trace
  7. Option
  8. Connect

The Servlet interface provides a protocol-independent request processing model javax.servlet. The HTTP package provides classes and interfaces for the HTTP based request processing.

Some commonly used HTTP classes are:

  • HttpServletRequest
  • HttpServletResponse
  • HttpServlet

Commonly used methods of HttpServlet are doGet() and doPost(). These are used to process HTTP get and post requests respectively.


  • public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException;
  • public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException;

Syntax to implemet HttpSpecific servlet

public MyServlet extends HttpServlet
  //Either doGet or doPost()
  // or both are used

In the syntax above we see that there are two methods, doGet() and doPost(), Now understand the differences between them.

There are the following differences between the doGet() and doPost() methods.

1. Conventionally get requests are used for static contents from the server and post requests are used for getting dynamic content from the server.

2. The technical difference is that a getRequest request is sent as part of a header size of a HTTP package header is fixed hence only a limited amount of data can be sent as part of a getRequest.

When PostRequest data is sent as part of a body, the size of the HTTP package body can be unlimited, hence an unlimited amount of data can be sent with a postRequest.

3. When getRequest requested data is append to the URL, it is visible in the address bar. The postRequest request data is not append to the URL, hence it is not visible in the address bar of the browser.

4. When getRequest requested data is transmitted over the network it is submitted by the user whereas postRequest requested data is encrypted using a standard 32-bit encryption algorithm and is transmitted over the network.

5. getRequest is idempotent postRequest is not.

Understand how to create a servlet using example.

In this example we create a servlet which takes user input names and displays them using the prefix "Welcome", as for example I provide a name "Sandeep" and it prints "Welcome Sandeep".

In this example we need to create the following classes:

  1. index.html
  2. web.xml
  3. MyFirstServlet.java

1. Index.html

This HTML file creates an interface in which the user enter his/her name and a submit button is used for processing the request.

2. web.xml

A XML file maps our servlet with the web-server. It provides the information of the application's components to the server. A simple web.xml for a servlet needs to provide the following information to the server in the web.xml file:

<servlet-name>Unique Identifier</servlet-name>
<servlet-name>Unique Identifier</servlet-name>
<url-pattern>URL need to invoke servlet</url-pattern>
</servlet mapping>

3. MyFirstServlet.java

This file contains servlet code in which we use either doGet() or doPost() methods. In this example we use the doPost() method.

To develop a servlet API we use the Netbeans IDE

The benefits of using this IDE is that we don't need to do the following things:

  • starting server manually
  • creating directory structure
  • creating web.xml file manually

Now we need to perform the following procedure.

Step 1

Open the Netbeans IDE.


Step 2

Choose "Java Web" -> "Web Application" then click on "Next", as shown below.


Step 3

Now type your project name and click on "Next".


Step 4

Choose your server and click on "Finish" as shown below.


Step 5

Now delete the index.jsp file and create a new HTML file with the name "index.html" as shown below.



Step 6

Now provide the following code for it.

<title>My First Servlet Page</title>
<form method="Post" action="MyFirstServlet">
Name: <input type="text" name="name"><br>
<input type="submit" value="submit">


Step 7

Now create a Java file as shown below.

Right-click on the project then select "New" -> "Servlet".


Step 8

Now click on "Next" and type your class name as "MyFirstServlet" then click on "Finish" as shown below.


Step 9

Now provide the following code for it.


import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class MyFirstServlet extends HttpServlet
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
        String name = request.getParameter("name");
        PrintWriter out = response.getWriter();
        out.println("Welcome " + name);


Step 10

In the Netbeans IDE we don't need to create a web.xml file; it is created by default by Netbeans. If you want to see this file then expand the project panel and click on "Web-Pages" then click on "WEB-INF". In this folder you will find the web.xml file.


Step 11

Now run your project and see the output as in the following:


Now pass a name, for example "Sandeep" and then click on the button. You will get the following output.


Thanks for reading