[java] How to create war files

What are the best practices of creating war files (using eclipse) to run on tomcat? tutorials, links, examples are highly appreciated.

This question is related to java eclipse tomcat war

The answer is


Use the Ant war task


Another common option is gradle.

http://www.gradle.org/docs/current/userguide/application_plugin.html

To build your war file in a web app:

In build.gradle, add:

apply plugin: 'war'

Then:

./gradlew war

Use the layout from accepted answer above.


**Making War file in Eclips Gaynemed of grails web project **

1.Import project:

2.Change the datasource.groovy file

Like this: url="jdbc:postgresql://18.247.120.101:8432/PGMS"

2.chnge AppConfig.xml

3.kill the Java from Task Manager:

  1. run clean comand in eclips

  2. run 'prod war' fowllowed by project name.

  3. Check the log file and find the same .war file in directory of workbench with same date.


Use the following command outside the WEB-INF folder. This should create your war file and is the quickest method I know.

(You will need JDK 1.7+ installed and environment variables that point to the bin directory of your JDK.)

jar -cvf projectname.war *

Reference Link


A war file is simply a jar file with a war extension, but what makes it work is how the contents is actually structured.

The J2EE/Java EE tutorial can be a start:

http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/WebComponents3.html

And the Servlet specification contains the gory details:

http://java.sun.com/products/servlet/download.html

If you create a new web project in Eclipse (I am referring to the Java EE version), the structure is created for you and you can also tell it where your Appserver is installed and it will deploy and start the application for you.

Using the "Export->WAR file" option will let you save the war file.


Another option would be to build it automatically using Eclipse. Of course if you have continuous integration environment Ant or Maven is recommended. The export alternative is not very convenient because you have to configure every time the export properties.

STEPS:

  1. Enable "Project Archives" support; this might depend on your project (I used it on Java EE/Web project). Right-click project root directory; Configure -> Add Project Archives Support.

  2. Go and create a new archive in the "Project Archives" top dir. You have only jar option, but name you archive *.war.

  3. Configure Fileset-s, i.e what files to be included. Typical is to configure two filesets similar how the Web Deployment Assembly (project property) is configured.

    • copy /WebContent to /
    • copy /build/classes to WEB-INF/classes (create this fileset after you define the WEB-INF/classes directory in the archive)
  4. You might need to tweek the fileset exclude property depending where you placed some of the config files or you might need more filesets, but the idea is that once you configured this you don't need to change it.

  5. Build the archive manually or publish directly to server; but is also automatically built for you by Eclipse


I've always just selected Export from Eclipse. It builds the war file and includes all necessary files. Providing you created the project as a web project that's all you'll need to do. Eclipse makes it very simple to do.


We use Maven (Ant's big brother) for all our java projects, and it has a very nifty WAR plugin. Tutorials and usage can be found there.

It's a lot easier than Ant, fully compatible with Eclipse (use maven eclipse:eclipse to create Eclipse projects) and easy to configure.

Maven's homepage

Maven WAR plugin

Sample Configuration:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.1-alpha-2</version>
    <configuration>
        <outputDirectory>${project.build.directory}/tmp/</outputDirectory>
        <workDirectory>${project.build.directory}/tmp/war/work</workDirectory>
        <webappDirectory>${project.build.webappDirectory}</webappDirectory>
        <cacheFile>${project.build.directory}/tmp/war/work/webapp-cache.xml</cacheFile>
        <nonFilteredFileExtensions>
            <nonFilteredFileExtension>pdf</nonFilteredFileExtension>
            <nonFilteredFileExtension>png</nonFilteredFileExtension>
            <nonFilteredFileExtension>gif</nonFilteredFileExtension>
            <nonFilteredFileExtension>jsp</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
        <webResources>
            <resource>
                <directory>src/main/webapp/</directory>
                <targetPath>WEB-INF</targetPath>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </webResources>
        <warName>Application</warName>
    </configuration>
</plugin>

If you are not sure what to do and are starting from scratch then Maven can help get you started.

By following the the below steps you can get a new war project setup perfectly in eclipse.

  1. Download and install Maven
  2. Go the command line run: mvn archetype:generate
  3. Follow the prompted steps - choosing the simple java web project (18) and a suitable name.
  4. When it is finished run: mvn eclipse:eclipse
  5. Start Eclipse. Choose File -> Import -> Existing project. Select the directory where you ran the mvn goals.
  6. That's it you should now have a very good start to a war project in eclipse
  7. You can create the war itself by running mvn package or deploy it by setting up a server in eclipse and simply adding adding the project to the server.

As some others have said the downside of using maven is that you have to use the maven conventions. But I think if you are just starting out, learning the conventions is a good idea before you start making your own. There's nothing to stop you changing/refactoring to your own preferred method at a later point.

Hope this helps.


Use ant build code I use this for my project SMS

<property name="WEB-INF" value="${basedir}/WebRoot/WEB-INF" />
<property name="OUT" value="${basedir}/out" />
<property name="WAR_FILE_NAME" value="mywebapplication.war" />
<property name="TEMP" value="${basedir}/temp" />

<target name="help">
    <echo>
        --------------------------------------------------
        compile - Compile
        archive - Generate WAR file
        --------------------------------------------------
    </echo>
</target>

<target name="init">
    <delete dir="${WEB-INF}/classes" />
    <mkdir dir="${WEB-INF}/classes" />
</target>

<target name="compile" depends="init">
    <javac srcdir="${basedir}/src" 
                destdir="${WEB-INF}/classes" 
                classpathref="libs">
    </javac>
</target>

<target name="archive" depends="compile">
    <delete dir="${OUT}" />
    <mkdir dir="${OUT}" />
    <delete dir="${TEMP}" />
    <mkdir dir="${TEMP}" />
    <copy todir="${TEMP}" >
        <fileset dir="${basedir}/WebRoot">
        </fileset>
    </copy>
    <move file="${TEMP}/log4j.properties" 
                    todir="${TEMP}/WEB-INF/classes" />
    <war destfile="${OUT}/${WAR_FILE_NAME}" 
                    basedir="${TEMP}" 
                    compress="true" 
                    webxml="${TEMP}/WEB-INF/web.xml" />
    <delete dir="${TEMP}" />
</target>

<path id="libs">
    <fileset includes="*.jar" dir="${WEB-INF}/lib" />
</path>


Simpler solution which also refreshes the Eclipse workspace:

<?xml version="1.0" encoding="UTF-8"?>
<project name="project" default="default">    
    <target name="default">
        <war destfile="target/MyApplication.war" webxml="web/WEB-INF/web.xml">
            <fileset dir="src/main/java" />
            <fileset dir="web/WEB-INF/views" />
            <lib dir="web/WEB-INF/lib"/>
            <classes dir="target/classes" />
        </war>
        <eclipse.refreshLocal resource="MyApplication/target" depth="infinite"/>
    </target>
</project>

Simplistic Shell code for creating WAR files from a standard Eclipse dynamic Web Project. Uses RAM File system (/dev/shm) on a Linux platform.

#!/bin/sh

UTILITY=$(basename $0)

if [ -z "$1" ] ; then
    echo "usage: $UTILITY [-s] <web-app-directory>..."
    echo "       -s ..... With source"
    exit 1
fi

if [ "$1" == "-s" ] ; then
    WITH_SOURCE=1
    shift
fi

while [ ! -z "$1" ] ; do
    WEB_APP_DIR=$1

    shift

    if [ ! -d $WEB_APP_DIR ] ; then
        echo "\"$WEB_APP_DIR\" is not a directory"
        continue
    fi

    if [ ! -d $WEB_APP_DIR/WebContent ] ; then
        echo "\"$WEB_APP_DIR\" is not a Web Application directory"
        continue
    fi

    TMP_DIR=/dev/shm/${WEB_APP_DIR}.$$.tmp
    WAR_FILE=/dev/shm/${WEB_APP_DIR}.war

    mkdir $TMP_DIR

    pushd $WEB_APP_DIR > /dev/null
    cp -r WebContent/* $TMP_DIR
    cp -r build/* $TMP_DIR/WEB-INF
    [ ! -z "$WITH_SOURCE" ] && cp -r src/* $TMP_DIR/WEB-INF/classes
    cd $TMP_DIR > /dev/null
    [ -e $WAR_FILE ] && rm -f $WAR_FILE
    jar cf $WAR_FILE .
    ls -lsF $WAR_FILE
    popd > /dev/null

    rm -rf $TMP_DIR
done

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to eclipse

How do I get the command-line for an Eclipse run configuration? My eclipse won't open, i download the bundle pack it keeps saying error log strange error in my Animation Drawable How to uninstall Eclipse? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Class has been compiled by a more recent version of the Java Environment Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9 "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Examples related to tomcat

Jersey stopped working with InjectionManagerFactory not found The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat Spring boot: Unable to start embedded Tomcat servlet container Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start Kill tomcat service running on any port, Windows Tomcat 8 is not able to handle get request with '|' in query parameters? 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE 403 Access Denied on Tomcat 8 Manager App without prompting for user/password Difference between Xms and Xmx and XX:MaxPermSize

Examples related to war

Deploying Java webapp to Tomcat 8 running in Docker container What is WEB-INF used for in a Java EE web application? How to unpackage and repackage a WAR file How to start jenkins on different port rather than 8080 using command prompt in Windows? Update Jenkins from a war file Oracle JDBC ojdbc6 Jar as a Maven Dependency UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class How to extract .war files in java? ZIP vs JAR How do I update a Tomcat webapp without restarting the entire service? Difference between jar and war in Java