Jetty 9.2 documentation gives a Jetty Embedded example to serve static files using a ResourceHandler
instead of a servlet :
// Create a basic Jetty server object that will listen on port 8080. Note that if you set this to port 0
// then a randomly available port will be assigned that you can either look in the logs for the port,
// or programmatically obtain it for use in test cases.
Server server = new Server(8080);
// Create the ResourceHandler. It is the object that will actually handle the request for a given file. It is
// a Jetty Handler object so it is suitable for chaining with other handlers as you will see in other examples.
ResourceHandler resource_handler = new ResourceHandler();
// Configure the ResourceHandler. Setting the resource base indicates where the files should be served out of.
// In this example it is the current directory but it can be configured to anything that the jvm has access to.
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[]{ "index.html" });
resource_handler.setResourceBase(".");
// Add the ResourceHandler to the server.
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
server.setHandler(handlers);
// Start things up! By using the server.join() the server thread will join with the current thread.
// See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more details.
server.start();
server.join();
Jetty uses NIO (in-memory file mapping) and thus locks files on Windows operating systems. This is a known issue and many workarounds can be found for servlets.
However, as this example does not rely on servlets, the associated answers based on webapp parameters (useFileMappedBuffer, maxCachedFiles) do not work.
In order to prevent in-memory file mapping, you need to add the following configuration line:
resource_handler.setMinMemoryMappedContentLength(-1);
Note: as written in the Javadoc (and noticed by nimrodm) : the minimum size in bytes of a file resource that will be served using a memory mapped buffer, or -1 for no memory mapped buffers
. I however got the same behavior with value Integer.MAX_VALUE
.
Once this parameter is set, your Jetty can serve static files on Windows AND you can edit them.