gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:30:32 25 4
gpt4 key购买 nike

希望在 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com