servlet

How Java Servlet Works

1. Introduction

In this article, we are going to look at a java servlet tutorial. “As opposed to what another language?” I hear you say and rightly so. Yes, servlets are a Java construct, but when compared with other languages they can easily be compared to those languages’ web component implementations. For the purposes of this article though, we will consider them as part Java’s web stack. So lets start the tutorial.

Do Servlets even still exist? Isn’t that outdated? Why would one even write an article about it? These are the thoughts that are running through my head when considering the topic and the answers are: No, no and because they are still very much alive. In fact they form the foundation of a number of shiny newer offerings in the Java web ecosystem.

2. A brief history of Servlets

While James Gosling is credited with the original idea of Servlets way back in 1995. The idea was parked until the Pavani Diwanji, now the VP of Engineering of Google, created the first Java Servlet V1 specification in 1997. Along with some of the core Java team, we owe a large debt of gratitude to her and not only in the java space.

In fact if you ever feel a little over confident or a bit “big for you boots” as a self styled “uber brain” a quick search of Pavani’s history will bring you back down to earth with a thud, very swiftly. This site alone https://patents.justia.com/inventor/pavani-diwanji should leave you feeling like a troglodyte. Pavani Diwanji, as a lover of all things tech I salute you! Ok, enough swooning! Let’s get down to the technical aspects.

3. What is a Java Servlet?

I like to think of Servlets as Java’s answer to “Dynamic Web Objects”. Similar to ASP.net in the Microsoft world or PHP. A lot of us don’t realise how much the API comes into play when building Java web based solutions, but a peek under the hood of your container certified container of choice will quickly show you that servlets are alive and well.

I am going to focus on the Java Servlet 4.0 Specification in this article https://jcp.org/aboutJava/communityprocess/final/jsr369/index.html. Why? because it’s the latest and greatest spec for Servlets and was released in 2017 as part of JEE 8 so it is very much alive and well. More importantly it is very relevant!

So servlets are platform independent Java based web components that are managed by containers. These components generate dynamic content. They are in actual fact Java classes that are compiled to byte code that can be dynamically loaded and run by java web servers. Servlets communicate with web clients via request/response within the servlet container.

The major addition to the servlet 4.0 specification is the HTTP 2.0 specification implementation. More importantly it now implements Server Push and NIO!

Servlets run in the “servlet containers” and with these containers comes a bouquet of benefits. For example security, thread handling, monitoring and all those lovely things that we need, but don’t want to focus on when building solutions in the real world under the ever present “time crunch!”

4. The Life Cycle of a Servlet

No explanation of servlets would be complete without a thorough understanding of the Servlet life cycle. Once we understand this from a component interaction perspective, Servlets become a lot simpler to implement. Especially in the context of multithreading and concurrency.

There are five main steps in the this life cycle:

  • Loading
  • Instantiation
  • Initialisation
  • Service
  • Destruction
Java Servlet - Servlets
Servlets
  1. When a request is received by the container for a Servlet. The class is loaded via the Class Loader.
  2. The container instantiates the servlet class.
  3. The init method which is found in the javax.servlet.Servletinterface is invoked by the web container.
  4. The service method is invoked once the above three steps have been completed. Thereafter every time this instance of the Servlet is required to fulfil a request the service method is invoked.
  5. Finally the container calls the destroy method in order to remove this instantiated class. At this point the servlet cleans up any memory or threads etc. that are no longer required.

5. Let’s build an example

In this example I am going to show you the Servlet interface implementation. Not too dissimilar to the steps listed in the previous section.

5.1. The boiler plate

First we simply create a class that implements the interface. We need to implement the methods and I have done so here, but without any functionality for now.

ServletLifeCycle.java

package com.jcg.example.servlet;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ServletLifeCycle implements Servlet {

	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}

5.2. The boiler plate with verbose comments

Next I want to got to to the Interface definition and get the relevant comments for the above required methods. That way we can see exactly what is required. I have not used all of the comments from the Servlet Interface. Just those that clarify the Servlet life cycle.

ServletLifeCycle.java

package com.jcg.example.servlet;

import java.io.IOException;

import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ServletLifeCycle implements Servlet {

	@Override //Servlet Life Cycle Method
	public void init(ServletConfig config) throws ServletException {
		/**
	     * Called by the servlet container to indicate to a servlet that the servlet
	     * is being placed into service.
	     *
	     * 
	     * The servlet container calls the init method exactly once
	     * after instantiating the servlet. The init method must
	     * complete successfully before the servlet can receive any requests.
	     *
	     * 
	     * The servlet container cannot place the servlet into service if the
	     * init method
	     * 
	     * Throws a ServletException
	     * Does not return within a time period defined by the Web server
	     * 
	     */
		
	}

	@Override 
	public ServletConfig getServletConfig() {
		/**
	     *
	     * Returns a {@link ServletConfig} object, which contains initialization and
	     * startup parameters for this servlet. The ServletConfig
	     * object returned is the one passed to the init method.
	     *
	     * 
	     * Implementations of this interface are responsible for storing the
	     * ServletConfig object so that this method can return it. The
	     * {@link GenericServlet} class, which implements this interface, already
	     * does this.
	     */
		return null;
	}

	@Override //Servlet Life Cycle Method
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		/**
	     * Called by the servlet container to allow the servlet to respond to a
	     * request.
	     *
	     *
	     * This method is only called after the servlet's init() method
	     * has completed successfully.
	     *
	     * 
	     * The status code of the response always should be set for a servlet that
	     * throws or sends an error.
	     *
	     *
	     * 
	     * Servlets typically run inside multithreaded servlet containers that can
	     * handle multiple requests concurrently. Developers must be aware to
	     * synchronize access to any shared resources such as files, network
	     * connections, and as well as the servlet's class and instance variables.
	     * More information on multithreaded programming in Java is available in 
	     * the Java tutorial on multi-threaded programming.
	     *
	     */
		
	}

	@Override
	public String getServletInfo() {
		/**
	     * Returns information about the servlet, such as author, version, and
	     * copyright.
	     *
	     * 
	     * The string that this method returns should be plain text and not markup
	     * of any kind (such as HTML, XML, etc.).
	     *
	     */
		return null;
	}

	@Override //Servlet Life Cycle Method
	public void destroy() {
		/**
	     * Called by the servlet container to indicate to a servlet that the servlet
	     * is being taken out of service. This method is only called once all
	     * threads within the servlet's service method have exited or
	     * after a timeout period has passed. After the servlet container calls this
	     * method, it will not call the servic method again on this
	     * servlet.
	     *
	     * 
	     * This method gives the servlet an opportunity to clean up any resources
	     * that are being held (for example, memory, file handles, threads) and make
	     * sure that any persistent state is synchronized with the servlet's current
	     * state in memory.
	     */
		
	}

}

The comments in the code above are taken straight out of the Servlet Interface. I thought, what better way to give a succinct understanding of how the Servlet life cycle works in Java, then to look at the contract defined by the Interface. I commented those methods which are part of the life cycle with “Servlet Life Cycle Method“.

5.3. The final class

Next let’s look at populating these methods without the comments so we have a practical implementation. This will give us a much better frame of reference.

ServletLifeCycle.java

package com.jcg.example.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/ServletLifeCycle")
public class ServletLifeCycle implements Servlet {
	
	private ServletConfig servletConfig = null;

	@Override //Servlet Life Cycle Method
	public void init(ServletConfig config) throws ServletException {
		
	    this.servletConfig = config;
	    System.out.println("Servlet has been loaded by the class loader and instantiated already!!!");
	    System.out.println("init(ServletConfig config) method invoked!");
	    System.out.println("Servlet Name: " + servletConfig.getServletName());
		
	}

	@Override
	public ServletConfig getServletConfig() {
		
		return this.servletConfig;
	}

	@Override //Servlet Life Cycle Method
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		System.out.println("service(ServletRequest req, ServletResponse res) method invoked!");
		
		//set content type for response
		res.setContentType("text/html");
		
		PrintWriter out = res.getWriter();
        out.print("com.jcg.example.servlet.ServletLifeCycle Example");
       

		
	}

	@Override
	public String getServletInfo() {
		
		return "JavaCodeGeeks Servlet Life Cycle Example";
	}

	@Override //Servlet Life Cycle Method
	public void destroy() {
		System.out.println("destroy() method invoked!");
		
		
	}

}

6. Java Servlet Example in Eclipse IDE

Let’s walk through a step by step tutorial on creating a Java Servlet in Eclipse IDE. Using Eclipse as an IDE makes the job much faster. The tutorial covers each step in detail and provides external links for more detail. So just put the seat belt on and be ready for the journey.

6.1 Downloading and Installing Eclipse IDE

Navigate to the link : https://www.eclipse.org/downloads/ and download the latest release of Eclipse IDE for Java Developers. A zip file would be downloaded in your system. Extract that zip file in your preferred location. To launch Eclipse, click on the Eclipse icon in the Eclipse folder extracted from the last step.

6.2 Installing and Configuring Tomcat in Eclipse

To run any web application including Servlets, a web server is required. For this example, we will be using Apache Tomcat server as it is one of the most famous web server and quite easy to configure.

  1. Navigate to the link : https://tomcat.apache.org/download-80.cgi .
  2. Scroll down the page to the ‘Binary Distributions’ section. Under it, you can see ‘Core’ section. From that section, download the zip file as per your Operating System.
  3. Extract the zip folder in any preferred location.
  4. In Eclipse, right click on the Servers tab located at the bottom. From the options, click on New->Server.
  5. Select Apache from the list and the appropriate version of the Tomcat server. Click Next.
  6. After that, in the dialog box that appears, populate the Tomcat installation directory as the location of the Tomcat folder extracted in Step 3.
  7. Click Finish.

6.3 Creating the Project

To make a Servlet enabled web project, follow the below steps :

  1. Launch Eclipse and then click on File -> New -> Dynamic Web Project.
  2. Mention the Project name as ‘ServletDemo’ and Target Runtime as Apache Tomcat and Click on Next.
  3. Enable the Checkbox which says ‘Generate web.xml deployment descriptor’.
  4. Click Finish.

The above steps set up the Project structure. Now we will download the javax servlet jar and include it in the build path of the project. Follow the below steps :

  1. Navigate to the link : https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api/3.0.1
  2. Download the JAR.
  3. Copy the JAR into the directory ServletDemo/WebContent/WEB-INF/lib.
  4. Right click on the Project ServletDemo and click on Build Path -> Configure Build Path.
  5. Add the JAR into the Build Path by browsing to the location ServletDemo/WebContent/WEB-INF/lib.

The above steps would allow us to use servlet API to create servlets in Eclipse. Now we will write code to create a Servlet. Follow the below steps :

  1. Right click on src folder in the Project and click on New -> Class and mention the class name as ServletDemo. This will open the Eclipse editor for the class ServletDemo. Write the below code in the ServletDemo class :

ServletDemo.java

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 ServletDemo extends HttpServlet{
	
	private String msg;
	
	@Override
	public void init() throws ServletException {
	      msg = "Welcome To Java Code Geeks";
	}

	@Override
	public void doGet(HttpServletRequest request,HttpServletResponse response)
	      throws ServletException, IOException 
	{

		// Setting up the content type of webpage
		response.setContentType("text/html");

		// Writing message to the web page
		PrintWriter out = response.getWriter();
		out.println("

" + msg + "

"); } @Override public void destroy() { /* leaving empty for now this can be * used when we want to do something at the end * of Servlet life cycle */ } }

A brief discussion on the above methods :

  1. init( ) : This method is called only for the first HTTP request and not for the subsequent requests. So this method is used for one time initializations.
  2. doGet( ) : All GET requests are handled by this method.
  3. destroy( ) : This method is called once at the end of the lifecycle of the servlet and is used to close external connections like DB connections, closing files etc.

Now we will create an HTML file index.html which will contain a link to call the servlet. The location of index.html would be ServletDemo/WebContent.

index.html

<!DOCTYPE html>
<html>
   <head>
   <meta charset="UTF-8">
      <title>Servlet Demo</title>
   </head>
   <body>
      <a href="welcome">Click to call Servlet</a>
   </body>
</html>

Now we need to map the Servlet to a specific URL. As we are calling welcome page upon clicking the link on the index.html so we are going to map the Servlet with the welcome page. The place to do this mapping is web.xml which is present in WebContent/WEB-INF/web.xml.

Web.xml is also called as deployment descriptor. The deployment descriptor describes the classes, resources and configurations of the web application. Whenever the web server receives a request for the web application, it uses web.xml to map the URL with the code that is made to handle that request. Web.xml resides at WEB-INF/web.xml.

web.xml

<?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" id="WebApp_ID" version="3.0">
  <display-name>ServletDemo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  
  <servlet>
	<servlet-name>ServletDemo</servlet-name>
	<servlet-class>ServletDemo</servlet-class>
  </servlet>

  <servlet-mapping>
	<servlet-name>ServletDemo</servlet-name>
	<url-pattern>/welcome</url-pattern>
  </servlet-mapping>

</web-app>

6.4 Run

Finally, to run this, right click on index.html and choose Run As -> Run on Server.

Eclipse will open the in-built browser with the address as http://localhost:8080/ServletDemo/index.html. You will see the link ‘Click to call Servlet’. Upon clicking the link, you will see the below output :

Welcome To Java Code Geeks

7. Conclusion

If you want to understand more about the technology, head over to jcp.org and check out JSR-000369. You can download the evaluation or implementations there too. I have not delved into the the juicy bits such as push and http2.0, but there are loads of great links and examples available for those out there for you to check out too.

8. Download the sample class

Download
You can download the full source code of this example here: How Java Servlet Works

Last updated on Sept. 24, 2019

Ed de Jongh

Ed has worked in the IT industry for over 20 years, gaining experience in programming, architecture and design. As a seasoned Solution Architect, he is passionate about advancing simplicity and elegance. In addition to solution design, he is also involved in development and integration. Outside of the office, enjoys anything on two wheels and being a dad.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button