向jetty添加多个资源目录

yoa*_*str 13 directory jetty embedded-jetty

希望在Jetty中使用多个静态目录.服务器运行时:

  http://localhost:8282/A
  http://localhost:8282/B 
  http://localhost:8282/C
Run Code Online (Sandbox Code Playgroud)
  • A放在X/V/A中
  • B放在Q/Z/B中
  • C放在P/T/C中

以下失败:

    ResourceHandler resource_handler = new ResourceHandler();
    resource_handler.setWelcomeFiles(new String[]{"index.html"});
    resource_handler.setResourceBase(HTML_SITE);

    ResourceHandler resource_handler1 = new ResourceHandler();
    resource_handler1.setWelcomeFiles(new String[]{"index.html"});
    resource_handler1.setResourceBase(HTML_CLIENTZONE_SITE);

    // deploy engine
    WebAppContext webapp = new WebAppContext();

    String dir = System.getProperty("user.dir");
    webapp.setResourceBase(getWebAppPath());
    webapp.setContextPath("/");


     HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]{resource_handler,resource_handler1 ,webapp,  new DefaultHandler()});
    server.setHandler(handlers);
Run Code Online (Sandbox Code Playgroud)

如何添加多个静态资源目录?

pna*_*pna 18

从6.1.12开始,通过对WebAppContext的基本资源使用ResourceCollection来支持此功能:

Server server = new Server(8282);
WebAppContext context = new WebAppContext();
context.setContextPath("/");
ResourceCollection resources = new ResourceCollection(new String[] {
    "project/webapp/folder",
    "/root/static/folder/A",    
    "/root/static/folder/B",    
});
context.setBaseResource(resources);
server.setHandler(context);
server.start();
Run Code Online (Sandbox Code Playgroud)

要随后打开文件,请使用ServletContext(例如,WebAppContext),它可以是接口定义的一部分,例如:

  /**
   * Opens a file using the servlet context.
   */
  public default InputStream open( ServletContext context, String filename ) {
    String f = System.getProperty( "file.separator" ) + filename;
    return context.getResourceAsStream( f );
  }
Run Code Online (Sandbox Code Playgroud)

如:

  InputStream in = open( context, "filename.txt" );
Run Code Online (Sandbox Code Playgroud)

filename.txt如果它存在于某个给定目录中,它将打开.请注意,getResourceAsStream将返回null,而不是抛出异常,因此检查它是个好主意:

  public default InputStream validate( InputStream in, String filename )
    throws FileNotFoundException {
    if( in == null ) {
      throw new FileNotFoundException( filename );
    }

    return in;
  }
Run Code Online (Sandbox Code Playgroud)

然后您可以open按如下方式更新方法:

return validate( context.getResourceAsStream( filename ), filename );
Run Code Online (Sandbox Code Playgroud)