A Brief Introduction To Servlets In Java

Introduction

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.

Servlets In Java

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.

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().

Syntax

  1. //implementation of Servlet through GenericServlet  
  2. public class MyServlet extends Generic Servlet  
  3. {  
  4.   //service() method is defined  
  5. }  

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.

Syntax

  • 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

  1. public MyServlet extends HttpServlet  
  2. {  
  3.   //Either doGet or doPost()   
  4.   // or both are used  
  5. }  

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

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.

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:

  1. <wep-app>  
  2.    <servlet-name>Unique Identifier</servlet-name>  
  3.       <servlet-class>Class-Name</servlet-class>  
  4.    </servlet>  
  5.    <servlet-mapping>  
  6.       <servlet-name>Unique Identifier</servlet-name>  
  7.    <url-pattern>URL need to invoke servlet</url-pattern>  
  8.    </servlet mapping>  
  9. </web-app>  

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.

Servlets In Java

Step 2

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

Servlets In Java

Step 3

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

Servlets In Java

Step 4

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

Servlets In Java

Step 5

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

Servlets In Java

Servlets In Java

Step 6

Now provide the following code for it.

  1. <html>  
  2.    <head>  
  3.       <title>My First Servlet Page</title>  
  4.    </head>  
  5.    <body>  
  6.       <form method="Post" action="MyFirstServlet">  
  7.          Name: <input type="text" name="name"><br>  
  8.          <input type="submit" value="submit">  
  9.       </form>  
  10.    </body>  
  11. </html>  

 

Servlets In Java

Step 7

Now create a Java file as shown below.

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

Servlets In Java

Step 8

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

Servlets In Java

Step 9

Now provide the following code for it.

MyFirstServlet.java

  1. import java.io.*;  
  2. import javax.servlet.http.*;  
  3. import javax.servlet.*;  
  4. public class MyFirstServlet extends HttpServlet  
  5.  {  
  6.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  7.             throws ServletException, IOException  
  8.  {  
  9.         String name = request.getParameter("name");  
  10.         response.setContentType("text/html");  
  11.         PrintWriter out = response.getWriter();  
  12.         out.println("Welcome " + name);  
  13.         out.close();  
  14.     }  
  15. }  

Servlets In Java

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.

Servlets In Java

Step 11

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

Servlets In Java

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

Servlets In Java

Thanks for reading


Similar Articles