如何使用来自不同项目的嵌入式jetty启动webapp

时间:2013-05-14 07:06:51

标签: web-applications jetty

这是一个简单的问题:是否可以从其他项目启动带有嵌入式码头的web-app? 我正在尝试运行(使用JUnit)以下代码:

Server server = new Server(80);
WebAppContext context = new WebAppContext();
File webXml = new File("../Project1/src/main/webapp/WEB-INF/web.xml");
context.setDescriptor(webXml.getAbsolutePath());
context.setResourceBase("../Project1/src/main/webapp");
context.setContextPath("/");
context.setParentLoaderPriority(false);
server.setHandler(context);
server.start();

如果我从另一个项目执行此操作,让我们说Project2,jetty抛出了很多例外: javax.servlet.UnavailableException:com.sun.xml.ws.transport.http.servlet.WSSpringServlet java.lang.ClassNotFoundException:com.sun.xml.ws.transport.http.servlet.WSSpringServlet

我已经尝试将Project1添加到Project的2类路径中,但这对情况没有帮助。 如果我尝试在相同的Project1中运行相同的(当然,调整了所有路径) - 一切正常。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

这可能是由于相对路径字符串造成的。

这是使用JUnit Assert的替代方法......

    Server server = new Server(80);
    WebAppContext context = new WebAppContext();
    File otherProject = new File("../Project1");
    Assert.assertTrue("Project1 should exist", otherProject.exists());

    // make path reference canonical (eliminate the relative path reference)
    otherProject = otherProject.getCanonicalFile();
    File webAppDir = new File(otherProject, "src/main/webapp");
    Assert.assertTrue("Webapp dir should exist", webAppDir.exists());
    File webXml = new File(webAppDir, "WEB-INF/web.xml");
    Assert.assertTrue("web.xml should exist", webXml.exists());

    context.setDescriptor(webXml.getAbsolutePath());
    context.setResourceBase(webAppDir.getAbsolutePath());
    context.setContextPath("/");
    context.setParentLoaderPriority(false);
    server.setHandler(context);
    server.start();

或者这可能是因为../Project1/src/main/webapp/WEB-INF/lib没有您需要的依赖项。这很重要,因为WebAppContext将首先使用提供的WEB-INF/lib内容,然后使用服务器类路径。

答案 1 :(得分:0)

所以我得到了解决方案,

您要么将原始的webapp项目包含为依赖项,要么使用自定义类加载器(如果不可能):

WebAppClassLoader customLoader = new WebAppClassLoader(context);
customLoader.addClassPath("../Project1/target/webapp/WEB-INF/classes");
Resource jars = Resource.newResource("../Project1/target/webapp/WEB-INF/lib");
customLoader.addJars(jars);
webapp.setClassLoader(customLoader);
相关问题