Home » Enterprise Java » servlet » How Java Servlet Works

About Ed de Jongh

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.

How Java Servlet Works

1. Introduction

In this article we are going to look at how the Java Servlet works. “As opposed to what other 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.

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 mother of Servlets 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 servlet 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 Servlet life cycle:

  • Loading
  • Instantiation
  • Initialisation
  • Service
  • Destruction
Java Servlet
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 Servlet 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 Servlet 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. Conclusion

So hopefully that gives you the reader a much clearer understanding of how Servlets work in Java. In particular the life cycle of servlets. 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.

7. Download the sample class

This was an example of how Java Servlet works.

Download
You can download the full source code of this example here: How Java Servlet Works
(+1 rating, 1 votes)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of