Servlets in Java

Servlets in Java

Servlets are used to create a web applications which resides at server-side and generates a dynamic web page. Java Servlets are one of the component APIs of Java Platform Enterprise Edition which sets standards for creating dynamic Web applications in Java. They act as a backbone for Java's Web Development, laying the groundwork for dynamic web applications. Servlets are Java objects that have special methods for handling the incoming HTTP requests by using various methods and it also provides the runtime environment for the execution of servlets.

How to execute Servlets?

Execution of Servlets involves six basic steps:

  1. The client sends the request to the web server.

  2. The web server receives the request.

  3. The web server passes the request to the corresponding servlet.

  4. The servlet processes the request and generates the response in the form of output.

  5. The servlet sends the response back to the web server.

  6. The web server sends the response back to the client and the client browser displays it on the screen.

Servlet Container

Servlets are managed by a Servlet Container, which can be a standalone web server or an application server like Apache Tomcat. Servlet Engine is an integrated set of objects that provide run time environment for Java Servlet components. In simple words, it is a system that manages Java Servlet components on top of Web Server to handle the Web Client requests.

Services provided by the Servlet Container:

  1. Network Services: Loads a Servlet class from a local file system, a remote file system or other network services. The Servlet Container provides the network services over which the request and response are sent.

  2. Decode and encode MIME-based messages: Provides the service of decoding and encoding MIME-based messages.

  3. Resource Management: Manages the static and dynamic resources, such as HTML files, Servlets and JSP pages.

  4. Security Services: Handles authorization and authentication of resource access.

  5. Session Management: Maintains a session by appending a session IDto the URL path.

Servlet Class Hierarchy

Servlet Interface

All servlets must implement the Servlet interface. It declares the init(), service() and destroy() methods that are called by the server during the life cycle of a servlet. These three methods are central to the life cycle of a servlet. They are implemented by every servlet and are invoked at specific times by the server.

A servlet can be defined as the entire process from its creation to its destruction. Let's consider a typical user scenario to understand when these methods are called.

  1. Assume that a user enters a URL in a web browser. The browser then generates an HTTP request for this URL. This request is then sent to the appropriate server.

  2. This HTTP request is received by the web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server.

  3. The server invokes the init( ) method of the servlet. This method is invoked only when the servlet is first loaded into the memory. It is possible to pass initialization parameters to the servlet so it may configure itself. It is used for one-time initializations.

  4. The server invokes the service( ) method of the servlet. This method is called to process the HTTP request. You will see that it is possible for the servlet to read data that has been provided in the HTTP request. It may also formulate an HTTP response for the client.

  5. The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients. The service( ) method is called directly by the server for each HTTP request.

  6. Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls the destroy( ) method to relinquish any resources such as file handles that are allocated for the servlet. Important data may be saved to a persistent store. The memory allocated for the servlet and its objects can then be garbage collected.

Basic implementation of the above discussed methods:

public void init() throws ServletException {
  // Initialization code...
}

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  // Servlet code...
}

public void destroy() {
  //...
}

ServletConfig Interface

The ServletConfig interface is implemented by the server. It allows a servlet to obtain configuration data when it is loaded. It is defined in the javax.servlet package. Each servlet has its own ServletConfig object, and servlets use their ServletConfig object to obtain initialization parameters and other information that they need in order to operate properly. The ServletConfig object is created by the web container when the servlet is initialized and it is passed to the servlet's init() method.

GenericServlet Class

GenericServlet implements the Servlet and ServletConfig interfaces and provides an implementation for all its method except service() method hence it is abstract. GenericServlet class defines a protocol-indepenedent i.e., HTTP-less servlet. However, when building a website we may want to have HTTP protocol, which is why we must extend the HttpServlet instead of GenericServlet. Developing servlet by extending GenericServlet is very easy because we only have to provide implementation for the service() method. GenericServlet class resides in the javax.servlet package.

Simple program using GenericServlet class:

import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
  public void service(ServletRequest request,ServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    pw.println("<B>Hello!");
    pw.close();
  }
}

HTTPServlet Class

The HttpServlet is an abstract class that extends GenericServlet and under the package javax.servlet.http.HttpServlet. It also implements the Serializable interface. It is commonly used when developing servlets that receive and process HTTP requests. To create a servlet the class must extend the HttpServlet class and override at least one of its methods (doGet, doPost, doDelete, doPut).

This is server-side code, it is only for clarification on how to use HttpServlet class.

import javax.servlet.*;
import javax.servlet.http.*;

public class GFGServlet extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res) {
    // User code to handle doGet request
  }

  public void doPost(HttpServletRequest req, HttpServletResponse res) {
    // User code to handle doPost request
  }
}

A list of all the important methods in the servlet hierarchy:

Conclusion

Newer technologies and frameworks like Spring MVC have gained popularity however, understanding the core concepts of Java Servlets remains essential as many of the newer technologies are built upon the foundations provided by Servlets. Mastering servets provides users with the essential skills such as hadling HTTP requets, managing sessions and understanding URL mapping - serving as the foundational knowledge that proves invaluable when progressing to more advanced frameworks.