Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Configuring an Embedded Jetty Server

Header Image

Ahoy, matey! Welcome aboard as we set sail on our journey to configure an Embedded Jetty Server. This article will guide you through the process of configuring your Embedded Jetty Server, including setting the port number and context path.

Setting the Port Number

Before we dive into configuring the server, let’s talk about the port number. The port number is like a dock number for ships to unload their cargo. Similarly, the port number is the address where the server listens for incoming requests.

By default, Jetty listens on port 8080. However, you can configure it to listen on any port of your choosing. To do this, you’ll need to modify the ServerConnector object in your code.

Here’s an example of how you can set the port number to 8888:

Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8888);
server.setConnectors(new Connector[] { connector });

With this code, Jetty will listen on port 8888 instead of the default port 8080.

Setting the Context Path

Now that we’ve set our port number, let’s move on to setting the context path. The context path is like a route to a specific dock in the port. Similarly, the context path is the URL path that maps to a specific web application on the server.

By default, Jetty’s context path is “/”. However, you can configure it to match the name of your web application. To do this, you’ll need to set the ContextHandler object in your code.

Here’s an example of how you can set the context path to “/myapp”:

Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8080);
server.setConnectors(new Connector[] { connector });

ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/myapp");
server.setHandler(context);

With this code, Jetty will map the URL path “/myapp” to your web application.

Conclusion

Huzzah! We’ve successfully configured our Embedded Jetty Server by setting the port number and context path. Remember, the port number is the address where the server listens for incoming requests, and the context path is the URL path that maps to a specific web application on the server.

Now, it’s time to hoist the sails and set off on your own adventure with Jetty. But before you do, don’t forget to check out the official Jetty documentation for more advanced configuration options and best practices.

Happy coding, matey!