我想要做的是构建一个包含我的项目的可执行文件JAR
。我已经包括它的依赖就在旁边,也JAR
文件,所以我的目录列表看起来是这样的:为JAR文件启动嵌入式jetty服务器
~/Projects/Java/web-app/out:
web-app.jar
dependency1.jar
dependency2.jar
dependency3.jar
我知道和相信我的问题没有从依赖出现,我的应用程序正常运行,直到我开始嵌入Jetty的那一刻。
我用来启动码头的代码是这样的:
public class ServerExecutionGoal implements ExecutionGoal {
private final static Logger logger = Logger.getLogger(ServerExecutionGoal.class);
private WebAppContext getWebAppContext() throws IOException {
WebAppContext context = new WebAppContext();
System.out.println("context = " + context);
context.setResourceBase(new PathMatchingResourcePatternResolver().getResource("classpath:/webapp").getURL().toExternalForm());
context.setContextPath("/");
context.setLogger(new StdErrLog());
return context;
}
@Override
public void execute(Map<String, Object> stringObjectMap) throws ExecutionTargetFailureException {
logger.info("Instantiating target server ...");
final Server server = new Server(8089);
final ContextHandlerCollection handlerCollection = new ContextHandlerCollection();
try {
handlerCollection.setHandlers(new Handler[]{new RequestLogHandler(), getWebAppContext()});
} catch (IOException e) {
throw new ExecutionTargetFailureException("Could not create web application context", e);
}
server.setHandler(handlerCollection);
try {
logger.info("Starting server on port 8089 ...");
server.start();
server.join();
logger.info("Server started. Waiting for requests.");
} catch (Exception e) {
throw new ExecutionTargetFailureException("Failed to properly start the web server", e);
}
}
public static void main(String[] args) throws ExecutionTargetFailureException {
new ServerExecutionGoal().execute(null);
}
}
我可以验证“Web应用程序”文件夹被我的JAR内正确地搬迁到/webapp
,并通过我的IDE中运行代码时( IntelliJ IDEA 11)context.setResourceBase(new PathMatchingResourcePatternResolver().getResource("classpath:/webapp").getURL().toExternalForm())
有效地映射到相关资源。此外,我可以证明它可以解决类似于:
jar:file:~/Projects/Java/web-app/out/web-app.jar!/webapp
并且可以访问(我读过它)。
然而,当我开始我的应用程序的主要方法,和Jetty开始,在http://localhost:8089
我得到如下:
HTTP ERROR: 503
Problem accessing /. Reason:
Service Unavailable
Powered by Jetty://
我要去哪里错了?
我知道通过设置“resourceBase”为“。”地址“http://localhost:8089
”将充当到位置“~/Projects/Java/web-app/out/
”的接口,在那里我可以看到所有JAR
文件的列表,包括“web-app.jar
”,点击我提供的下载文件。
我已经看到了下面的问题,答不适用:
- Embedded jetty application not working from jar:我得到NullPointerException异常,因为
Start.class.getProtectionDomain().getCodeSource()
解析为null
。 - Embedded Jetty WebAppContext FilePermission issue:这不仅没有回答,但情况显然不适用,因为我没有权限问题(我可以得到一个文件列表应该证明这一点)。
- embedding jetty server problems:也没有答案,也不适用,因为我没有任何依赖性问题(正如我在前面的评论中指出的那样)。
我认为我应该以某种方式使码头访问/webapp
文件夹,它位于我src/main/resources/
目录下,并捆绑到我的Web应用程序。我应该放弃一个捆绑的Web应用程序,并将爆炸的上下文路径部署到Jetty可访问的地方(这完全不可取,因为它会给我和我的客户带来许多问题)。
你可以用一个WAR文件使用context.setWar(...)。这只会将一个文件添加到您的发行版中。 –
我也面临类似的问题。当服务器从eclipse启动时,我得到了正确的请求响应。但是从cmd的jar文件运行时,我得到了404。任何帮助表示赞赏。 –