使用 Java 将网络应用程序上传到 tomcat

Upload web app to tomcat using Java

在我的单元测试中,我使用 org.apache.catalina.startup.Tomcat 来部署网络应用程序。我能够毫无问题地部署 .war 格式的网络应用程序。 但就我而言,我想将 java 代码中的值添加到 webapp 的 index.html,然后上传。所以我不能坚持使用 .war 格式。我尝试上传网络应用程序,因为 directory.Following 是我的 java 代码,用于将 "examplewebapp" 作为目录上传。

    String appPath="/home/examplewebapp"; // webapp
    String currentDir = new File(".").getCanonicalPath();
    String tomcatDir = currentDir + File.separatorChar + "tomcat";


    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir(tomcatDir);
    tomcat.setPort(4040);
    tomcat.addWebapp("/examplewebapp", appPath);        
    tomcat.start();

但 Web 应用程序未按预期部署在服务器上。我需要知道是否 tomcat.addWebapp() 方法仅支持 .war 格式或者我的代码中有任何错误。

第 1 步:咨询 Lars Vogel's 4th chapter of his tutorial how to add Tomcat in Eclipse 并按照他的说明进行操作。

第 2 步:单击您的 Web 项目并转到第 3 步。

第 3 步:单击 运行 并让 Eclipse 启动您的 Tomcat。

第 4 步:Select 'Run on Server' 然后按确定继续。

第 5 步:选择现有服务器并可选择启用复选框。

第 6 步:尽情享受吧!

我认为上面的代码有两个错误

首先你没有找到正确文件夹的路径 (String appPath="/home/examplewebapp"; // webapp)

第二个你需要打电话 tomcat.getServer().await();在 tomcat.start() 之后;因为服务器启动后会退出

看下面的例子

字符串 webappDirLocation = "src/main/webapp/"; Tomcat tomcat = 新 Tomcat();

    //The port that we should run on can be set into an environment variable
    //Look for that variable and default to 8080 if it isn't there.
    String webPort = System.getenv("PORT");
    if(webPort == null || webPort.isEmpty()) {
        webPort = "8080";
    }

    tomcat.setPort(Integer.valueOf(webPort));

    tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
    System.out.println("configuring app with basedir: " + new File("./" + webappDirLocation).getAbsolutePath());

    tomcat.start();
    tomcat.getServer().await();
}