logo

Creating File Server with Embedded Jetty Server in Java

In this tutorial you will learn simple step by step to write an Java application which using Embedding Jetty API to creating a static file server.

The very first step you need to do is add Jetty Server dependency to your project.

Using Gradle

compile group: 'org.eclipse.jetty', name: 'jetty-server', version: '9.4.15.v20190215'

Using Maven

<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-server</artifactId>
    <version>9.4.15.v20190215</version>
</dependency>

To listen HTTP request at a specified port we need to create org.eclipse.jetty.server.Server object and provide port number.

Server server = new Server(9090);

In order to serve static file via the port above we are creating org.eclipse.jetty.server.handler.ResourceHandler object. This object will handle requests and serve static contents.

ResourceHandler resourceHandler = new ResourceHandler();

To enable our file server to show directories we need to set directory allow to true.

resourceHandler.setDirAllowed(true);

Then configure where to read files to serve by setting resource base, for example code below to set current directory of the program:

resourceHandler.setResourceBase(".");

Final step to set resource handle object to server and start your file server.

server.setHandler(resourceHandler);

server.start();
server.join();

Notice that we have server.join() method above to join the Embedded Jetty server thread with the current application thread.

That’s all you need for a simple file server using Embedded Jetty, the full source code look like below:

package simplesolution.dev;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ResourceHandler;

public class EmbeddedJettyFileServer {

    public static void main(String... args) throws Exception {
        Server server = new Server(9090);

        ResourceHandler resourceHandler = new ResourceHandler();
        resourceHandler.setDirAllowed(true);
        resourceHandler.setResourceBase(".");
        server.setHandler(resourceHandler);

        server.start();
        server.join();
    }
}

Let run above program then open your browser and navigate to http://localhost:9090 you will see the static files will serve as below:

File Server powered by Embedded Jetty

The source code in this article can be found at: https://github.com/simplesolutiondev/EmbeddedJettyFileServer

Happy Coding!

Tags: