create a executable jar using maven and jetty

眉间皱痕 提交于 2019-11-28 07:52:37

Take a look at http://uguptablog.blogspot.com/2012/09/embedded-jetty-executable-war-with.html

The relevant code is

    ProtectionDomain domain = Main.class.getProtectionDomain();
    URL location = domain.getCodeSource().getLocation();
    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setWar(location.toExternalForm());
    server.setHandler(webapp);

hope that helps.

Gili

Instead of hacking the contents of a WAR file, as the accepted answer seems to be doing, you can create an executable JAR file using the maven-shade-plugin. This has the following advantages:

  • The plugin contains "transformers" for merging the contents of META-INF/services, LICENSE and README files.
  • You end up with a JAR file. WAR files were not designed to be executable (although it works).
  • By unpacking all dependencies into the same JAR file, you are forced to remove duplicate classes and make the contents harder to reverse-engineer.

If you are not tied to using Jetty but are open to using Tomcat instead, the following will work beautifully:

<plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.0</version>
    <executions>
        <execution>
            <id>tomcat-run</id>
            <goals>
                <goal>exec-war-only</goal>
            </goals>
            <phase>package</phase>
            <configuration>
                <path>/standalone</path>
                <enableNaming>false</enableNaming>
                <finalName>standalone.jar</finalName>
                <charset>utf-8</charset>
            </configuration>
        </execution>
    </executions>
</plugin>

This will create an uberjar called "standalone.jar" that you can then run simply by calling

java -jar standalone.jar

this will start the application on http://localhost:8080/standalone

Selecting an alternate port is easy

java -jar standalone.jar -httpPort=7070

Thanks to Tomasz Nurkiewicz's blog entry for highlighting this http://www.nurkiewicz.com/2012/11/standalone-web-application-with.html

The simpliest way I know (but never tried) is the , like Jenkins CI do (what a better example :D). It doesn't use Jetty (even I love this tool :D), but Winstone.

Maven Plugin Usage

<plugin>
    <groupId>net.sf.alchim</groupId>
    <artifactId>winstone-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>embed</goal>
            </goals>
            <phase>package</phase>
        </execution>
    </executions>
</plugin>

Quite easy, isn't it ? :) It would generate a executable - standalone - jar : app-dca-1.0-standalone.jar

Documentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!