使用嵌入式Jetty提供静态文件 [英] Serving static files with embedded Jetty

查看:563
本文介绍了使用嵌入式Jetty提供静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用嵌入式Jetty构建一个简单的演示应用程序,该应用程序提供来自html目录的静态文件,该目录是当前工作目录的子目录。这个想法是带有演示jar和内容的目录可以移动到新的位置并且仍然可以工作。

I'm trying to build a simple demo app with embedded Jetty that serves static files from a "html" directory that's a subdirectory of the current working directory. The idea is that the directory with the demo jar and content can be moved to a new location and still work.

我尝试了以下的变体,但我保留得到404s。

I've tried variations of the following, but I keep getting 404s.

ServletContextHandler context = 
                       new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");

context.getInitParams().put(
                       "org.eclipse.jetty.servlet.Default.resourceBase", "html");
context.addServlet(new ServletHolder(new DefaultServlet()), "/html");

Server jetty = new Server(8080);
jetty.setHandler(context);

jetty.start();

更新:以下是Jetty教程中记录的解决方案。正如在正确答案中所提到的,它使用 ResourceHandler 而不是 ServletContextHandler

Update: Here's a solution as documented in the Jetty tutorial. As mentioned in the correct answer, it uses a ResourceHandler instead of a ServletContextHandler:

    Server server = new Server();
    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(8080);
    server.addConnector(connector);

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

    resource_handler.setResourceBase(".");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
    server.setHandler(handlers);

    server.start();
    server.join();


推荐答案

使用 ResourceHandler 而不是 ServletContextHandler

这篇关于使用嵌入式Jetty提供静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆