directory - 向 jetty 添加多个资源目录

标签 directory jetty embedded-jetty

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

  http://localhost:8282/A
  http://localhost:8282/B 
  http://localhost:8282/C
  • 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);
    

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

    最佳答案

    从 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();
    

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

      /**
       * 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 );
      }
    

    如:

      InputStream in = open( context, "filename.txt" );
    

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

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

    然后你可以更新open方法如下:

    return validate( context.getResourceAsStream( filename ), filename );
    

    关于directory - 向 jetty 添加多个资源目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11410388/

    相关文章:

    java - jetty 服务器 Web 应用程序和 lib 文件的自动更新程序

    ubuntu - DocumentRoot 没有改变,从 Apache2 2.2.22 更新到 2.4.7

    ruby - 如何更轻松地运行此脚本

    linux - 两个文件大小相同但文件名不同的目录之间的差异

    java - Jetty 嵌入式服务器 - 更改部署 war 文件的路径

    java - 嵌入式 Jetty 是否能够设置过滤器的初始参数?

    maven - 配置 maven-shade-plugin 以包含 src/main/webapp

    winapi - 是什么导致 CreateDirectory 返回 ERROR_ACCESS_DENIED?

    jetty 空闲超时

    java - 如何配置 jetty 以使用 log4j?