Skip to main content

Command Palette

Search for a command to run...

Web Programming In Java

Updated
4 min readView as Markdown
Web Programming In Java
J
Software Engineer for quite a few years. From C programmer to Java web programmer. Very interested in automated testing and functional programming, operating systems, embedded programming.

1. Introduction and Fundamentals: What is a Servlet?

  • Base definition: A Servlet is not an external framework; it is a specialized Java class that is part of the official specification (belonging to the jakarta.servlet or javax.servlet package depending on the version).

  • Role in architecture and protocol: It acts as a server-side component that receives HTTP requests (Requests) from a client and generates an HTTP response (Response). The HTTP protocol regulates communication between a client computer and a server computer, specifying the content of messages (headers and body). All of this specification is translated into Java code thanks to the implementation of the Servlet interface, or more specifically, the corresponding abstract class.

  • Lifecycle: Managed by a web container using the init(), service(), and destroy() methods.

Flowchart

https://mermaid.live/edit#pako:eNqNUttu00AQ\_ZXRPCCQQurYcWJbKC8pagSIojRVBfLLxjskpvauuzuGhij\_zvqSS\_vEPs2Ozplz5rLHTEvCBC091aQyus7FxogyVeCeqFmrulyT6f8ZawPzIifFXaYShvMsr4Ri-ETMOxC2D-7I\_D4SL2FNviBugN91bWDBXPW5VHXwTuH9bNZWSuDm4wqutlQUGlJcij-wWK2-wbKxbDnFjvRVM4F2ktCzbitSFqzOHokHYEhIC-sdk\_2wNlczoSSUorLAWwJ6ZjJKFHC\_\_DLsyrVFzhbmju-oR1F44yJbaWWd5voXZWxf0vqOErAuyDN6a-ipMWHfvXZ7Ql4TN3W65krirZauXdd7iifHhmRuWlSuOsvFrjfc17nUlvqG-D-U2z0UepNn\_ZjcvoRzQOY8qw0pMu0IUly0q3jQppApvpI\_j-zB5A2c3XCBdeOgm9day93lsByjW3gCvufB7eeXS-5YKeIANyaXmLCpaYAlmVI0X9w3xVJ0eywdLHGhFOaxOYuD47ib-6F1eaQZXW-2mPwUhXW\_upKupf7mTxBSksxc14oxGXltCUz2-IyJPw6HURwGcRT6fjSJRwPcuWwwDL0oCMJoGvuhP\_WDwwD\_tqLeMPL9ySQIvOkoiuPxaHz4B41sI5Q

Sequence Diagram

https://mermaid.live/edit#pako:eNqNU8tu20AM\_BViD0ULqI4cyS-h8MUpYvSVwnURtNBlLbG2GmlX4VJtXMP\_XuplJ82lOnEpznA43D2oxKaoIuXwvkKT4FWmt6SLmGID8umKramKDdIpk7AlWOQZGu5zpSbOkqzUhuEdMu9Buy74gvTrDH5cWP\_JkevSb7YiWDKXXa4u7yFtp9fzecMXwfXbNVzsMM8txGqlf8Nyvf4Mq1q-41j1sE-WEay0hg53U6Jx4Gxyh-wBoU4dbPaM7s2GLubapFDo0gHvEPCBkYzO4evqw6AnbGjOMhbCIOC-MbyQyJXWOOm6-YkJu3-B3WwROAmyBF8S3tdC3Kvnmk-1V8g1VztkgbyzqYwtHsTqpJswzaipykwrPN-fZHdMj\_un9hr5v7o3e8ntNks6w2R\_WlQgnV3bokFqrIjVslnLraU8jdUzCWfzbimrASxGA9taRevcxqb7p7YJpr0AEVz6Pty8f7r0FtduXXlqS1mqIqYKPVUgFbo-qkNNGCvZbCGlkYSppjsBmaNg5C5-t7boYWSr7U5FP3Tu5FSVqYzWvYlTCZoUaWErwyoaTv2GQ0UH9dAcB6OJH8z8ySQIw2E49tRe0rPBeOj7gT8bDS-DcDwOjp7607T1B9PJSDKTcCqwIBzOPCULlUf2sX2ZzQM9\_gXSKTdY


2. Servlet Container

Unlike other languages like Python or Node.js/JavaScript—whose standard libraries do include classes and functions to implement a web server—Java follows a different philosophy. The Java standard offers an interface, as explained in the previous section, to which all web servers must conform if they want to be compatible with that specification. Some of the most famous ones are Tomcat and GlassFish.

To have a real servlet container (that is, one that complies with the jakarta.servlet specification and processes HttpServlet), you cannot do it solely with the base JDK classes because, as we saw, the JDK provides the interfaces but not the container engine.


3. Jetty

The easiest, most modern, and lightweight way to have a functional servlet container without manually setting up heavy servers like Tomcat or GlassFish is to use Embedded Jetty, just as we saw in the first code example.

What is Jetty?

It is a Java web server and servlet container known for being extremely lightweight, high-performing, and having a very small memory footprint compared to traditional corporate heavyweights.

Ideal Use Cases

  • Microservices architectures where every megabyte of RAM matters when scaling containers.

  • Embedded systems or devices with heavily limited hardware resources.

Why is Embedded Jetty the Easiest Way?

  1. No XML configuration files: You don't need to deploy web.xml files or package a .war file.

  2. Self-contained: Everything runs from a simple main method inside a .class file or an executable .jar file.

  3. Minimal boilerplate code: With fewer than 25 lines of code, you initialize the port, define the context, and launch the servlet container in memory.

Ultra-short Example with Maven and Embedded Jetty

If you configure a Maven project by adding only the core Jetty dependencies (jetty-server and jetty-servlet), you can instantiate the container directly like this:

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import jakarta.servlet.http.*;
import java.io.IOException;

public class ContenedorMinimo {
    public static void main(String[] args) throws Exception {
        // 1. Instantiate the container on port 8080
        Server server = new Server(8080);

        // 2. Create the servlet context handler
        ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS);
        handler.setContextPath("/");
        server.setHandler(handler);

        // 3. Add our Servlet class directly to the container
        handler.addServlet(new ServletHolder(new HttpServlet() {
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
                resp.getWriter().write("Servlet Container is running!");
            }
        }), "/");

        // 4. Start the engine
        server.start();
        server.join();
    }
}

4. Spring, Quarkus, and Similar Frameworks

Any other alternative (such as Spring Boot) does this exact same thing under the hood, but adds automatic abstraction layers, integrating an embedded container by default (such as Tomcat or Jetty). By using annotations and controlling the object lifecycle, they hide all internal plumbing at the cost of higher startup memory consumption.

  • Current abstraction: Modern production tools and frameworks like Spring (and its evolution Spring Boot) build on top of the Servlet API.

  • Benefits of the leap: Spring Boot radically simplifies development by managing dependency injection, advanced routing, security, and configuration via annotations, shielding the developer from direct servlet complexity while maintaining the exact same underlying foundation. This is why it's so extreamily used industry.