Servlet in nutshell

What is Servlet

A servlet is a Java program that runs in a Web server, as opposed to an applet that runs in a client browser. Typically, the servlet takes an HTTP request from a browser, generates dynamic content (such as by querying a database), and provides an HTTP response back to the browser. Alternatively, the servlet can be accessed directly from another application component or send its output to another component. Most servlets generate HTML text, but a servlet may instead generate XML to encapsulate data.

More specifically, a servlet runs in a J2EE application server. Servlets are one of the main application component types of a J2EE application, along with JavaServer Pages (JSP) and EJB modules, which are also server-side J2EE component types.

Prior to servlets, Common Gateway Interface (CGI) technology was used for dynamic content, with CGI programs being written in languages such as Perl and being called by a Web application through the Web server. CGI ultimately proved less than ideal, however, due to its architecture and scalability limitations.

Servlet containers, sometimes referred to as servlet engines, execute and manage servlets. The servlet container calls servlet methods and provides services that the servlet needs while executing. A servlet container is usually written in Java and is either part of a Web server (if the Web server is also written in Java) or is otherwise associated with and used by a Web server.

key class

  • javax.servlet.Servlet -> javax.servlet.GenericServlet -> javax.servlet.http.HttpServlet
  • javax.servlet.http.HttpSession
  • javax.servlet.ServletContext
  • HttpRequest
  • HttpResponse

What is filter

A Servlet filter is an object that can intercept HTTP requests targeted at your web application.

Description of Figure 3-1  follows

The order in which filters are invoked depends on the order in which they are configured in the web.xml file. The first filter in web.xml is the first one invoked during the request, and the last filter in web.xml is the first one invoked during the response. Note the reverse order during the response.

What is event listener

The servlet specification includes the capability to track key events in your Web applications through event listeners. This functionality allows more efficient resource management and automated processing based on event status.

The event classes are as follows:

  1. ServletRequestEvent
  2. ServletContextEvent
  3. ServletRequestAttributeEvent
  4. ServletContextAttributeEvent
  5. HttpSessionEvent
  6. HttpSessionBindingEvent
Event Listener Categories and Interfaces
Event Category Event Descriptions Java Interface
Servlet context lifecycle changes Servlet context creation, at which point the first request can be serviced

Imminent shutdown of the servlet context

javax.servlet. ServletContextListener
Servlet context attribute changes Addition of servlet context attributes

Removal of servlet context attributes

Replacement of servlet context attributes

javax.servlet. ServletContextAttributeListener
Session lifecycle changes Session creation

Session invalidation

Session timeout

javax.servlet.http. HttpSessionListener
Session attribute changes Addition of session attributes

Removal of session attributes

Replacement of session attributes

javax.servlet.http. HttpSessionAttributeListener



Hypermedia API

What is the term? “The simultaneous presentation of information and controls such that the information becomes the affordance through which the user obtains choices and selects actions.” – Roy Fielding

To understand this, we need first to understand what is the benefit: decouple client and server of RESTful API. In current API development, the client follows the API specification and any change at server side will break the client code.

How to solve this? Image if the client follow the action told by the server and the code is adaptive enough to the actions. Then the server can evolve independently.

HATEOAS, an abbreviation for Hypermedia as the Engine of Application State, is a constraint on the REST application architecture.

Check out some examples:


Array data structure VS. ArrayList class

Array is a “legend” data type but ArrayList is part of the Collection framework. So what is the difference between them?

  1. ArrayList is “Resizable-array implementation of the List interface.” But array is fixed length.
  2. ArrayList.size() is a method call but array.length is internal variable
  3. Both support type safety: you have to specify data type when define it.
  4. ArrayList only support Object so no primitive type. This is due the List<E> is defined via generic type. Any primitive type is casted to corresponding object.

Now let look at a sample code to see some other difference:

package basic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListDemo {
	public static void main(String[] args){
		String[] str = new String[10];
		str[2] = "c";
		List<String> list = new ArrayList<String>(str.length);
		System.out.println("list1 size: " + list.size());
		System.out.println("list1 size: " + list.size());
//		list.add(2, "c");
		List<String> list2 = new ArrayList<String>();
		list2 = Arrays.asList(str);

Please note the line commented out. Even you create ArrayList with initial capacity. But the size is still 0! Following source code explains why:

    public ArrayList(int initialCapacity) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
        this.elementData = new Object[initialCapacity];

If you uncomment that line, you will get following exception:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
	at java.util.ArrayList.rangeCheckForAdd(
	at java.util.ArrayList.add(
	at basic.ArrayListDemo.main(

When you add element, the size will increase and make sure resize it:

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;

This post doesn’t talk about performance. But here is what my judgment: in Java, always try to use Collection framework instead of raw date type like array. The reason is simple: you application especially commercial  software, will be built and improved by many iterations, so try to make it generic to adapt any change late. For example, defining an interface to accept and return List<E> will make your life much easier compare to Object[]. Performance is an overall evaluation not just a class.