gpt4 book ai didi

嵌入式 jetty 的 Java web.xml 位置

转载 作者:行者123 更新时间:2023-12-01 09:42:32 27 4
gpt4 key购买 nike

我试图了解我们应该如何配置 Web 应用程序。现在我有一个带有嵌入式 jetty 的简单 gradle 项目

layout structure

依赖关系:

dependencies {
compile('org.eclipse.jetty:jetty-servlet:9.3.10.v20160621')
compile('org.eclipse.jetty:jetty-webapp:9.3.10.v20160621')

testCompile group: 'junit', name: 'junit', version: '4.11'
}

应用程序主:

package test;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

public class App {
public static void main(String[] args) throws Exception {

System.out.println(">> Running");
WebAppContext webAppContext = new WebAppContext();
webAppContext.setDescriptor("src/main/resources/WEB-INF/web.xml");
webAppContext.setResourceBase("/");
webAppContext.setContextPath("/");

Server server = new Server(8080);
server.setHandler(webAppContext);
server.start();
server.join();
}
}

在 web.xml 中,我仅定义了 ServletContextListener 实现来查找它是否被应用程序捕获。

我的问题是:webAppContext.setDescriptor("src/main/resources/WEB-INF/web.xml")Jetty 只能通过这个奇怪的位置路径找到 web.xml。

为什么我需要从项目文件夹中定位它?如果我使用 gradle 运行 jar 任务,则 jar 内不会有任何 src 目录。

是否存在类似以下内容的方法:App.class.getResource("/WEB-INF/web.xml")并加载与类路径相关的web.xml?

最佳答案

似乎是一些类加载器问题。

经过一些进一步的搜索,我以下一个解决方案结束:

public class App {
private static final String WEBAPP_RESOURCES_LOCATION = "webapp";

public static void main(String[] args) throws Exception {
System.out.println(">> Running");

WebAppContext webAppContext = new WebAppContext();
webAppContext.setContextPath("/");

URL webAppDir = Thread.currentThread().getContextClassLoader().getResource(WEBAPP_RESOURCES_LOCATION);
webAppContext.setResourceBase(webAppDir.toURI().toString());

// if setDescriptor set null or don't used jetty looking for /WEB-INF/web.xml under resource base
// webAppContext.setDescriptor(webAppDir.toURI().toString() + "web.xml");

Server server = new Server(8080);
server.setHandler(webAppContext);
server.start();
server.join();
}
}

布局:

enter image description here

感谢 github 用户 arey 提供的示例 examle

关于嵌入式 jetty 的 Java web.xml 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38344654/

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