Using Jetty to Embed a Web Server | Generated by AI

Home PDF

To use org.eclipse.jetty in a Java project, you typically want to leverage the Jetty libraries to embed a lightweight web server or servlet container within your application. Jetty, maintained under the Eclipse Foundation, is an open-source project that allows you to serve web content, handle HTTP requests, and support features like servlets and web applications. Below is a step-by-step guide to get you started with using org.eclipse.jetty to set up a basic web server in a Java application using Maven as the build tool.


Step 1: Add Jetty Dependencies to Your Project

To use Jetty, you need to include its libraries in your project. If you’re using Maven, add the necessary dependencies to your pom.xml file. For a basic web server setup with servlet support, include jetty-server and jetty-servlet. Here’s an example:

<project>
    <dependencies>
        <!-- Jetty Server -->
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.4.31.v20200723</version>
        </dependency>
        <!-- Jetty Servlet Support -->
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>9.4.31.v20200723</version>
        </dependency>
        <!-- Servlet API (optional, often included transitively) -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

Note: Check the Maven Central Repository for the latest Jetty version and update the <version> tag accordingly.


Step 2: Create a Simple Jetty Server

You can use Jetty programmatically by creating an instance of the Server class from the org.eclipse.jetty.server package. Below are two common approaches: using a basic handler for static responses or using a servlet for dynamic content.

Option 1: Using a Basic Handler

This example sets up a server that responds with “Hello, World!” to all requests.

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SimpleJettyServer {
    public static void main(String[] args) throws Exception {
        // Create a server instance listening on port 8080
        Server server = new Server(8080);

        // Set a handler to process requests
        server.setHandler(new AbstractHandler() {
            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
                    throws IOException {
                // Set response properties
                response.setContentType("text/plain");
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().println("Hello, World!");

                // Mark the request as handled
                baseRequest.setHandled(true);
            }
        });

        // Start the server
        server.start();
        server.join(); // Keeps the server running until stopped
    }
}

Run this code, then open a browser and navigate to http://localhost:8080/ to see “Hello, World!”.

Option 2: Using a Servlet

For more complex applications, you can use servlets with a ServletContextHandler.

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ServletJettyServer {
    public static void main(String[] args) throws Exception {
        // Create a server instance on port 8080
        Server server = new Server(8080);

        // Create a servlet context handler
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/"); // Root context path

        // Set the handler for the server
        server.setHandler(context);

        // Add a servlet to handle requests
        context.addServlet(new ServletHolder(new HelloServlet()), "/*");

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

// Define a simple servlet
class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("text/plain");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println("Hello from Jetty Servlet!");
    }
}

Run this code and visit http://localhost:8080/ to see “Hello from Jetty Servlet!”.


Step 3: Compile and Run

  1. Ensure your project is set up with Maven (e.g., run mvn compile to download dependencies).
  2. Compile and run the Java class (e.g., java SimpleJettyServer or use your IDE’s run feature).
  3. Test the server by accessing http://localhost:8080/ in a browser or using a tool like curl.

Additional Use Cases


Key Points

By following these steps, you can effectively use org.eclipse.jetty to embed a web server in your Java application, tailored to your specific needs!


Back 2025.03.06 Donate