We have come a long way since the introduction of Servlets back in 1999. Back then, implementing and getting to run a Servlet required a lot of development, class overloading, XML configuration and a host of other tasks. It prompted improvements like Java Servlet pages and the subsequent move towards frameworks like the model-view-controller model with Struts that have evolved from framework to framework to where we are today, with powerful frameworks like Spring Boot, Micronaut et al. But the Servlet component has not remained idle through those times.

The benefits of these frameworks are undeniable and have simplified the creation of Servlets, we tend exclusively use these frameworks now for any HTTP content serving like Web pages and Restful services.

The simplicity has come at a price, though, where a simple single page application, like the ‘Hello world!’ example project, now compiles into a massive 63Mb! Luckily the Servlet component development hasn’t been idle and creating a Servlet without a framework has become quite a lot simpler to the point that going without a framework has become a feasible choice.

Since Servlet spec 3.1, the Servlet component supports the use of annotations that are recognized by most of the main stream Servlet containers. Creating a Servlet can now be as simple as:

import java.io.IOException;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/helloworld")
public class HelloWorldServlet extends HttpServlet {
	private static final long serialVersionUID = 7874848560427888696L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.getWriter().append("<html><body><h1>Hello World!</h1</body></html>");
	}
}

And that is all. Compile it into either a JAR or WAR file and deploy it to any Servlet container and it will be picked up and run automatically. And without the overhead of a full framework it will compile down to just over 1kb!

Similarly, you can use @WebFilter to simply add filters to your code as well. So next time you need only a simple page, API or other web function added to an application, don’t automatically grab for an entire framework but consider skipping framework in favour of just the basic Servlet component.

shadow-left