Examples / Server Examples / Hello World: Embedded Jetty (Command Line)

Hello World: Embedded Jetty (Command Line)

example java server jetty

This example contains an HTML file and a servlet class, as well as a class with a main() method that runs an embedded Jetty server.


<!DOCTYPE html>
    <title>Embedde Jetty Hello World</title>
    <h1>Embedded Jetty Hello World</h1>
    <p>Hello world!</p>


package io.happycoding;

import java.io.IOException;

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

public class HelloWorldServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    response.getWriter().println("<h1>Hello world!</h1>");


package io.happycoding;

import java.net.URL;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.webapp.WebAppContext;

 * Starts up a server that serves static files from the top-level directory and
 * automatically loads servlets annotated with the @WebServlet annotation.
public class ServerMain {

  public static void main(String[] args) throws Exception {

    // Create a server that listens on port 8080.
    Server server = new Server(8080);
    WebAppContext webAppContext = new WebAppContext();

    // Load static content from the top level directory.
    URL webAppDir = ServerMain.class.getClassLoader().getResource(".");

    // Look for annotations in classes and packages in the top level directory.
        "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/");

    // Start the server! 🚀
    System.out.println("Server started!");

    // Keep the main thread alive while the server is running.

You can view the directory here or download it as a zip file here.

See the Embedded Jetty tutorial for instructions on compiling and running this example.

Comments and Questions

Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!