在没有maven的情况下启动jetty的可执行war文件

时间:2010-03-16 21:54:23

标签: java executable jetty manifest war

我正在尝试制作一个“可执行”war文件(java -jar myWarFile.war),该文件将启动一个Jetty网络服务器,该网络服务器托管我执行的WAR文件中包含的webapp。

我发现a page描述了如何制作我正在寻找的东西:

然而,遵循这个建议以及我认为我应该制作一个可执行jar(战争)的方式是行不通的。

我有一个Ant任务创建一个带有清单的WAR文件,如下所示:

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 1.5.0_18-b02 (Sun Microsystems Inc.)
Main-Class: Start

WAR文件的内容如下:

> Start.class
> jsp
>   build.jsp 
> META-INF  
>   MANIFEST.MF
> WEB-INF
>   lib
>     jetty-6.1.22.jar
>     jetty-util.6.1.22.jar

当我尝试执行WAR文件时,错误是:

Exception in thread "main" java.lang.NoClassDefFoundError: org/mortbay/jetty/Handler
Caused by: java.lang.ClassNotFoundException: org.mortbay.jetty.Handler
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: Start. Program will exit.

这里似乎有两个错误:一个似乎无法找到JAR文件,另一个找不到Start类。

要修复第一个,我将Jetty JAR文件放在WAR文件的基础上并再次尝试 - 同样的错误。我还尝试将WEB-INF/lib/<specific-JAR-files>添加到清单的Class-Path属性中。这也不起作用。

有没有人对我正确/错误以及如何启动并运行此可执行WAR文件有任何见解?

9 个答案:

答案 0 :(得分:50)

您问题中的link提供了您需要的大部分内容。但是,除此之外还有一些事情需要做。

Jetty需要启动的任何类文件都需要在打包时位于war文件的根目录下。在我们<war>文件之前,我们可以利用Ant为我们做这件事。 war的manifest文件还需要一个Main-Class属性来执行服务器。

以下是一步一步:

创建Jetty服务器类:

这是根据您提供的链接改编的。

package com.mycompany.myapp;

import java.io.File;
import java.net.URL;
import java.security.ProtectionDomain;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;

public final class EmbeddedJettyServer
{
    public static void main(String[] args) throws Exception
    {
        int port = Integer.parseInt(System.getProperty("port", "8080"));
        Server server = new Server(port);

        ProtectionDomain domain = EmbeddedJettyServer.class.getProtectionDomain();
        URL location = domain.getCodeSource().getLocation();

        WebAppContext webapp = new WebAppContext();
        webapp.setContextPath("/");
        webapp.setDescriptor(location.toExternalForm() + "/WEB-INF/web.xml");
        webapp.setServer(server);
        webapp.setWar(location.toExternalForm());

        // (Optional) Set the directory the war will extract to.
        // If not set, java.io.tmpdir will be used, which can cause problems
        // if the temp directory gets cleaned periodically.
        // Your build scripts should remove this directory between deployments
        webapp.setTempDirectory(new File("/path/to/webapp-directory"));

        server.setHandler(webapp);
        server.start();
        server.join();
    }
}

要查看您在此处可以配置的内容,请查看Jetty API documentation

与Ant建立战争:

这使用一个临时目录将必要的类文件解压缩到战争的根目录中,以便在执行战争时可以访问它们。

<target name="war" description="--> Creates self-executing war">
  <property name="staging.dir" location="${basedir}/staging"/>
  <property name="webapp.dir" location="${basedir}/src/webapp"/>

  <mkdir dir="${staging.dir}"/>

  <!-- assumes you have all of your war content (excluding classes and libraries) already structured in a directory called src/webapp -->
  <!-- e.g. -->
  <!-- src/webapp/index.html -->
  <!-- src/webapp/WEB-INF/web.xml -->
  <!-- src/webapp/WEB-INF/classes/my.properties -->
  <!-- etc ... -->
  <copy todir="${staging.dir}">
    <fileset dir="${webapp.dir}" includes="**/*"/>
  </copy>

  <unjar dest="${staging.dir}">
    <!-- you'll have to locate these jars or appropriate versions; note that these include JSP support -->
    <!-- you might find some of them in the downloaded Jetty .tgz -->
    <fileset dir="path/to/jetty/jars">
      <include name="ant-1.6.5.jar"/>
      <include name="core-3.1.1.jar"/>
      <include name="jetty-6.1.24.jar"/>
      <include name="jsp-2.1-glassfish-2.1.v20091210.jar"/><!-- your JSP implementation may vary -->
      <include name="jsp-api-2.1-glassfish-2.1.v20091210.jar"/><!-- your JSP implementation may vary -->
      <include name="servlet-api-2.5-20081211.jar"/><!-- your Servlet API implementation may vary -->
    </fileset>
    <patternset><!-- to exclude some of the stuff we don't really need -->
      <exclude name="META-INF/**/*"/>
      <exclude name="images/**/*"/>
      <exclude name=".options"/>
      <exclude name="about.html"/>
      <exclude name="jdtCompilerAdapter.jar"/>
      <exclude name="plugin*"/>
    </patternset>
  </unjar>

  <!-- copy in the class file built from the above EmbeddedJettyServer.java -->
  <copy todir="${staging.dir}">
    <fileset dir="path/to/classes/dir" includes="com/mycompany/myapp/EmbeddedJettyServer.class"/>
  </copy>

  <war destfile="myapp.war" webxml="${webapp.dir}/WEB-INF/web.xml">
    <fileset dir="${staging.dir}" includes="**/*"/>
    <classes dir="path/to/classes/dir"/><!-- your application classes -->
    <lib dir="path/to/lib/dir"/><!-- application dependency jars -->
    <manifest>
      <!-- add the Main-Class attribute that will execute our server class -->
      <attribute name="Main-Class" value="com.mycompany.myapp.EmbeddedJettyServer"/>
    </manifest>
  </war>

  <delete dir="${staging.dir}"/>
</target>

执行战争:

如果一切都在上面正确设置,你应该能够:

java -jar myapp.war

// or if you want to configure the port (since we are using the System property in the code)

java -Dport=8443 -jar myapp.war

答案 1 :(得分:45)

这是对@ RobHruska的答案Maven的改编。它只是复制主类的文件并将Jetty JAR文件合并到WAR文件中,没有什么新东西,只是为了简化你的生活,如果你是像Maven这样的新人:

<plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <executions>
        <execution>
            <id>move-main-class</id>
            <phase>compile</phase>
            <configuration>
                <tasks>
                    <copy todir="${project.build.directory}/${project.build.finalName}">
                        <fileset dir="${project.build.directory}/${project.build.finalName}/WEB-INF/classes/">
                            <include name="main/*.class" />
                        </fileset>
                    </copy>

                    <unjar dest="${project.build.directory}/${project.build.finalName}">
                        <!-- you'll have to locate these jars or appropriate versions; note that these include JSP support -->
                        <!-- you might find some of them in the downloaded Jetty .tgz -->
                        <fileset dir="${project.build.directory}/${project.build.finalName}/WEB-INF/lib/">
                            <include name="ant-1.6.5.jar"/>
                            <!--<include name="core-3.1.1.jar"/>-->
                            <include name="jetty*"/>
                            <include name="servlet-api*"/>
                        </fileset>

                        <patternset><!-- to exclude some of the stuff we don't really need -->
                            <exclude name="META-INF/**/*"/>
                            <exclude name="images/**/*"/>
                            <exclude name=".options"/>
                            <exclude name="about.html"/>
                            <exclude name="jdtCompilerAdapter.jar"/>
                            <exclude name="plugin*"/>
                        </patternset>
                    </unjar>
                </tasks>
            </configuration>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
    </executions>
</plugin> 
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.2</version>
    <configuration>
        <archiveClasses>true</archiveClasses>
        <archive>
            <manifest>
                <mainClass>main.Main</mainClass> 
            </manifest>
        </archive>
    </configuration>
</plugin>

答案 2 :(得分:14)

我们已经通过使用jetty-console-maven-plugin来解决这个问题。

无论何时运行mvn包,它都会创建另一个可以与java -jar一起使用的war-whatever-runnable.war

        <plugin>
            <groupId>org.simplericity.jettyconsole</groupId>
            <artifactId>jetty-console-maven-plugin</artifactId>
            <version>1.45</version>
            <executions>
                <execution>
                    <goals>
                        <goal>createconsole</goal>
                    </goals>
                </execution>
            </executions>

            <configuration>
                <additionalDependencies>
                    <additionalDependency>
                        <artifactId>jetty-console-requestlog-plugin</artifactId>
                    </additionalDependency>
                    <additionalDependency>
                        <artifactId>jetty-console-gzip-plugin</artifactId>
                    </additionalDependency>
                    <additionalDependency>
                        <artifactId>jetty-console-ajp-plugin</artifactId>
                    </additionalDependency>
                    <additionalDependency>
                        <artifactId>jetty-console-startstop-plugin</artifactId>
                    </additionalDependency>
                </additionalDependencies>
            </configuration>
        </plugin>

它还会为您生成init.d脚本和所有内容!

答案 3 :(得分:7)

Hudson使用Winstone servlet容器解决了这个确切的问题,该容器直接支持这个用例。 http://winstone.sourceforge.net/#embedding

也许这对你有用吗?

答案 4 :(得分:6)

即使这是旧的另一种替代Jetty 8只是简单地将Jetty jar作为依赖项包含在你的pom中并在你的pom中添加以下内容(相对于解包战争并重新打包它的ant脚本):

            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>1.4</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <createDependencyReducedPom>true</createDependencyReducedPom>
                        <transformers>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>JettyStandaloneMain</mainClass>
                            </transformer>
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <!-- The main class needs to be in the root of the war in order to be 
            runnable -->
        <plugin>
            <artifactId>maven-antrun-plugin</artifactId>
            <executions>
                <execution>
                    <id>move-main-class</id>
                    <phase>compile</phase>
                    <configuration>
                        <tasks>
                            <move todir="${project.build.directory}/${project.build.finalName}">
                                <fileset dir="${project.build.directory}/classes/">
                                    <include name="JettyStandaloneMain.class" />
                                </fileset>
                            </move>
                        </tasks>
                    </configuration>
                    <goals>
                        <goal>run</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

答案 5 :(得分:3)

我认为“没有maven”你想要一个可以独立运行的jar而不是“mvn jetty:run” - 而不是你根本不想使用maven。

我花了很长时间才弄明白,因为我发现了许多选择 - 其中没有一个简单。最后我找到了this maven plugin from simplericity。它运作得非常好。

答案 6 :(得分:1)

这是我的ANT提取示例。我们的想法是解压缩Jetty依赖项,然后像普通的JAR文件一样在本地包含它们:

         

<!-- Hack: Java doesn't support jars within jars/wars -->
<unjar src="${lib.dir}/container/jetty.jar" dest="${build.dir}/unjar"/>
<unjar src="${lib.dir}/container/jetty-util.jar" dest="${build.dir}/unjar"/>
<unjar src="${lib.dir}/container/servlet-api.jar" dest="${build.dir}/unjar"/>
<unjar src="${lib.dir}/container/jsp-api.jar" dest="${build.dir}/unjar"/>

<!-- Build war file as normal, just including the compiled and unjar'ed files -->
<war destfile="${war.file}" webxml="${config.dir}/web.xml">
    <fileset dir="${build.dir}/classes"/>
    <fileset dir="${build.dir}/unjar"/>
    <fileset dir="${resources.dir}" excludes="*.swp"/>
    <lib dir="${lib.dir}/runtime"/>
    <manifest>
        <attribute name="Main-Class" value="Start"/>
    </manifest>
</war>

注意:

WEB-INF / lib 目录用于Web应用程序依赖项。在这种情况下,我们打包WAR文件,使其像启动时的普通Jetty JAR文件一样工作

答案 7 :(得分:0)

  • 将.jars放在.war文件根目录中
  • 将.jars放在WEB-INF/lib中无助于JVM发现Jetty文件甚至开始启动.war。将它们放在那里“为时已晚”。
  • 将.jars放在清单Class-Path中仅适用于外部.jar文件,而不适用于.jar中包含的文件

那该怎么办?

  • 使用构建脚本将所需的所有.jar文件合并到.war文件中。这需要一些额外的工作。它也有点难看,因为编译的代码是.war
  • 中可服务文件的一部分
  • 使用“java -cp jetty.jar:......”将依赖的.jars添加到JVM的类路径中。虽然这样做可以挫败一个独立的目的.war

答案 8 :(得分:0)

之前我做过类似的事情,但你是否将应用程序称为“java -jar xxx.war”?你只有2个罐子,我觉得这还不够。另请尝试使用Jetty 7.0.0M1(这是最新版本)。当我添加jetty-server和jetty-webapp作为两个依赖项(它们来自org.eclipse.jetty)时,我在lib目录中获得了以下jar。仅供参考org.mortbay.jetty.Handler在jetty-server * .jar中。

  • 码头 - 连续 - 7.0.0.M1.jar
  • 码头-HTTP-7.0.0.M1.jar
  • 码头-IO-7.0.0.M1.jar
  • 码头-安全7.0.0.M1.jar
  • 码头 - 服务器 - 7.0.0.M1.jar
  • 码头-servlet的7.0.0.M1.jar
  • jetty-util-7.0.0.M1.jar
  • 码头-web应用-7.0.0.M1.jar
  • 码头-XML的7.0.0.M1.jar