使用 web.xml 以编程方式启动码头

Using web.xml to conf programmatically started jetty

我创建了一个eclipse maven 项目并添加了jetty 依赖。接下来我制作了一个简单的 servlet 和一个启动码头服务器的 class。这是我到目前为止得到的:

package com.example.jetty;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;

public class App {
    public static void main(String[] args) throws Exception {
        Server server = new Server(80);
        ServletContextHandler servletContext = new ServletContextHandler(server, "/");
        servletContext.addServlet(MyServlet.class, "/");
        server.start();
    }
}

我的问题是我看到的大多数教程都有 web.xml 来配置 servlet 等。我找不到执行其中一些操作的编程方法。我可以创建一个 web.xml 并仍然以编程方式启动我的码头并以某种方式使用 web.xml 进行配置吗?

更具体地说,我需要在 web.xml 中写入 true。我没有找到任何编程方式。

我将从一个您可能感兴趣的示例开始。如果您想以编程方式使用 web.xml Jetty 服务器,那么您可以执行以下操作:

WebAppContext context = new WebAppContext();
context.setContextPath("/myWebApp");
context.setExtractWAR(false);
context.setDescriptor("/file/system/path/to/your/wab/app/WEB-INF/web.xml");
context.setResourceBase("/file/system/path/to/your/wab/app");
context.setConfigurationDiscovered(false);

HandlerList handlerList=new HandlerList();
handlerList.addHandler(webAppContext);

Server server = new Server(threadPool);
server.setHandler(handlerList);
server.start();

关于以编程方式配置,您可以尝试使用 Servlet 3.x API,它受 Jetty 8.x(当前 Jetty 版本 9.x)和可以通过编程方式完全配置。