Jetty 9.2 documentation给出了Jetty Embedded示例,使用 ResourceHandler 而不是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使用NIO(内存中文件映射),因此locks files on Windows operating systems . 这是一个已知问题,可以找到servlet的许多变通方法 .
但是,由于此示例不依赖于servlet,因此基于webapp参数(useFileMappedBuffer,maxCachedFiles)的相关答案不起作用 .
为了防止内存中文件映射,您需要添加以下配置行:
resource_handler.setMinMemoryMappedContentLength(-1);
注意:如在Javadoc中所写(并且由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 . 然而,我的值与 Integer.MAX_VALUE 具有相同的行为 .
设置此参数后,您的Jetty可以在Windows上提供静态文件,您可以编辑它们 .