【问题标题】:Using web.xml to conf programmatically started jetty使用 web.xml 以编程方式启动码头
【发布时间】:2017-02-24 00:34:18
【问题描述】:

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

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。我没有找到任何以编程方式执行此操作的方法。

【问题讨论】:

标签: java eclipse jetty


【解决方案1】:

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

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

关于以编程方式配置,您可以尝试使用Jetty 8.x(当前Jetty 版本9.x)支持的Servlet 3.x API,并且可以完全以编程方式配置。

【讨论】:

  • 感谢您的回答。我是否正确理解只有当我想以编程方式配置它时才需要这个 servlet 3.x api 依赖项?您是否还知道如何使用此 api 配置异步支持的属性的示例?
  • 要启用Servlet 3.0,您需要在web.xml 中指定version="3.0",其他所有内容都可以留空,因此您可以将此类web.xml 放在类路径中而不是文件系统中。 @WebServlet 带参数asyncSupported = true 可用于async-supported
  • here 你可以找到JettyServlet 3.0 的示例
猜你喜欢
  • 2020-04-29
  • 2022-10-08
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 1970-01-01
  • 2013-07-03
相关资源
最近更新 更多