Build WAR File in Java

Su Suriya Ravichandran Updated 18 Nov 2026
9 min read ·Lesson 266 of 306

A WAR (Web Application Archive) file packages a Java web application so a servlet container such as Apache Tomcat can deploy it. To build WAR file in Java projects, you put your compiled classes, libraries and web pages into a fixed folder layout and let Maven or Gradle zip them into one .war file.

This lesson explains what goes inside a WAR, builds one with Maven and with Gradle, shows why the Servlet API uses the provided scope, and deploys the result to Tomcat. It ends with a versioned release that Tomcat can swap in without downtime. If you need a runnable desktop or command-line program instead, see Build Executable JAR in Java.


What Is a WAR File in Java?

A WAR file is a ZIP file with a standard layout defined by the Jakarta Servlet specification. The container reads this layout to find your classes, libraries and settings.

Path inside the WARContainsVisible to browsers?
/ (root)HTML, CSS, JavaScript, images, JSP filesYes
/WEB-INF/classes/Your compiled .class files and resourcesNo
/WEB-INF/lib/Library JARs your app needs at run timeNo
/WEB-INF/web.xmlOptional deployment descriptor (servlet mappings, welcome files)No
/META-INF/MANIFEST.MFArchive metadataNo

JAR vs WAR

JARWAR
Started byjava -jar app.jarA servlet container (Tomcat, Jetty, GlassFish)
Needs main methodYes, for executable JARsNo
LibrariesUnpacked (fat JAR) or in lib/ next to itInside WEB-INF/lib
Servlet APIMust be bundled if usedSupplied by the container

How it works:

  • Anything under WEB-INF is private. A request for /WEB-INF/web.xml returns 404, so your classes and settings are never downloaded.
  • The container gives each WAR its own class loader. Two apps can use different versions of the same library without clashing.

Project Layout for a Java Web Application

Maven and Gradle both expect web files in src/main/webapp. This lesson uses a small app called student-portal.

student-portal/
├── pom.xml                      <- or build.gradle.kts
└── src/main/
    ├── java/com/gocourse/portal/
    │   └── HelloServlet.java    <- compiled into WEB-INF/classes
    └── webapp/
        ├── index.html           <- copied to the WAR root
        └── WEB-INF/
            └── web.xml          <- optional

The servlet answers requests to /hello:

package com.gocourse.portal;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String studentName = request.getParameter("name");
        if (studentName == null || studentName.isBlank()) {
            studentName = "student";
        }
        response.setContentType("text/plain;charset=UTF-8");
        response.getWriter().println("Hello, " + studentName + "!");
    }
}

How it works:

  • @WebServlet("/hello") tells the container which URL this class handles, so web.xml is not required.
  • The jakarta.servlet packages come from the Servlet API. Tomcat 10 and later use jakarta.*; very old tutorials use javax.servlet.*, which does not work on Tomcat 10+.
  • Servlets are covered in depth in Java Servlet Basics. Here the focus is packaging.

Build a WAR File With Maven

Set <packaging>war</packaging> and add the Servlet API with the provided scope.

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.gocourse</groupId>
  <artifactId>student-portal</artifactId>
  <version>1.0.0</version>
  <packaging>war</packaging>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!-- Tomcat 11 supplies this at run time -->
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
      <version>6.1.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>student-portal</finalName>
    <plugins>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.4.0</version>
      </plugin>
    </plugins>
  </build>
</project>
mvn -q package
jar tf target/student-portal.war

Output:

META-INF/
META-INF/MANIFEST.MF
WEB-INF/
WEB-INF/classes/
WEB-INF/classes/com/
WEB-INF/classes/com/gocourse/
WEB-INF/classes/com/gocourse/portal/
WEB-INF/classes/com/gocourse/portal/HelloServlet.class
index.html
WEB-INF/web.xml
META-INF/maven/com.gocourse/student-portal/pom.xml
META-INF/maven/com.gocourse/student-portal/pom.properties

How it works:

  • packaging=war switches the package phase from the JAR plugin to the WAR plugin, which builds target/student-portal.war.
  • finalName drops the version from the file name. The file name becomes the URL path in Tomcat, so student-portal.war is served at /student-portal.
  • Compiled classes go to WEB-INF/classes, and everything in src/main/webapp is copied to the WAR root.
  • WEB-INF/lib is missing because the only dependency is provided.

Note: Since version 3.0 the WAR plugin no longer fails when web.xml is missing. Annotation-only apps can delete src/main/webapp/WEB-INF/web.xml completely.


Why the Servlet API Uses Provided Scope

The container already ships the Servlet API in its own lib folder. Your WAR needs the API to compile, but must not carry its own copy at run time.

Maven scopeGradle configurationOn compile classpathInside WEB-INF/lib
compileimplementationYesYes
runtimeruntimeOnlyNoYes
providedprovidedCompileYesNo
testtestImplementationTests onlyNo

Add a normal library, Gson, and see where each dependency lands:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.13.2</version>
</dependency>
mvn -q package
jar tf target/student-portal.war | grep WEB-INF/lib

Output:

WEB-INF/lib/
WEB-INF/lib/gson-2.13.2.jar
WEB-INF/lib/error_prone_annotations-2.41.0.jar

How it works:

  • Gson has the default compile scope, so it and its transitive dependency are copied into WEB-INF/lib.
  • The Servlet API JAR is not there, because Tomcat provides jakarta.servlet-api itself. Two copies of the same API on one class path can cause confusing ClassCastException and LinkageError problems.
  • Dependency scopes are explained fully in Maven Dependencies.

Build a WAR File With Gradle

Gradle has a built-in war plugin. It adds the war task and the providedCompile and providedRuntime configurations.

// build.gradle.kts
plugins {
    war
}

group = "com.gocourse"
version = "1.0.0"

repositories { mavenCentral() }

java {
    toolchain { languageVersion = JavaLanguageVersion.of(21) }
}

dependencies {
    providedCompile("jakarta.servlet:jakarta.servlet-api:6.1.0")
    implementation("com.google.code.gson:gson:2.13.2")
}

tasks.war {
    archiveFileName = "student-portal.war"   // fixed name, no version
}
./gradlew war -q
jar tf build/libs/student-portal.war | grep -E "classes/.*class|lib/|html"

Output:

index.html
WEB-INF/classes/com/gocourse/portal/HelloServlet.class
WEB-INF/lib/gson-2.13.2.jar
WEB-INF/lib/error_prone_annotations-2.41.0.jar

How it works:

  • The war plugin applies the java plugin too, so src/main/java is compiled as usual.
  • providedCompile is Gradle's equivalent of Maven's provided scope.
  • ./gradlew build also runs war, because the plugin makes assemble depend on it.
  • archiveFileName controls the output name in build/libs.

Add Extra Files to the WAR

Both tools can copy files from other folders. In Gradle, use from inside tasks.war:

tasks.war {
    archiveFileName = "student-portal.war"
    from("docs") {
        into("help")          // docs/guide.html -> /help/guide.html
    }
    webInf {
        from("config/app.properties")   // -> WEB-INF/app.properties
    }
}

How it works:

  • from(...) { into(...) } adds public files under a new folder in the WAR root.
  • webInf { } adds private files under WEB-INF, where browsers cannot reach them but your code can read them with getServletContext().getResourceAsStream("/WEB-INF/app.properties").

Deploy a WAR File to Apache Tomcat

Tomcat 11 implements Servlet 6.1 and needs Java 17 or later. Deploying is as simple as copying the WAR into the webapps folder.

# Start Tomcat in the foreground so the log prints in this terminal
$CATALINA_HOME/bin/catalina.sh run

In a second terminal:

cp target/student-portal.war $CATALINA_HOME/webapps/
curl -s "http://localhost:8080/student-portal/hello?name=Asha"

Output in the Tomcat terminal (shortened):

INFO [Catalina-utility-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive [/opt/tomcat/webapps/student-portal.war]
INFO [Catalina-utility-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive [/opt/tomcat/webapps/student-portal.war] has finished in [312] ms

Output from curl:

Hello, Asha!

How it works:

  • Tomcat checks webapps every few seconds (autoDeploy). It unpacks student-portal.war into a student-portal/ folder and starts the app.
  • The context path comes from the file name: student-portal.war is served at /student-portal, and ROOT.war is served at /.
  • To redeploy, copy a new WAR over the old one. To undeploy, delete the WAR and Tomcat removes the unpacked folder too.

Context Path Rules

WAR file nameURL
student-portal.warhttp://localhost:8080/student-portal/
ROOT.warhttp://localhost:8080/
api#v1.warhttp://localhost:8080/api/v1/
shop##003.warhttp://localhost:8080/shop/ (version 003)

How it works:

  • A single # in the name becomes a / in the path, so you can deploy nested context paths.
  • Text after ## is a version label. It is not part of the URL; the next section uses it for zero-downtime releases.

Inspect a WAR Before You Ship It

Check the contents before copying a WAR to a server. A missing class or an extra Servlet API JAR is easier to fix on your machine.

CommandWhat it shows
jar tf app.warEvery entry in the archive
jar tf app.war | grep WEB-INF/libBundled libraries
unzip -p app.war WEB-INF/web.xmlThe deployment descriptor
mvn dependency:tree -Dscope=runtimeWhy a library was included (Maven)
./gradlew dependencies --configuration runtimeClasspathThe same for Gradle
jar tf target/student-portal.war | grep -c "servlet-api"

Output:

0

How it works:

  • grep -c counts matching lines. 0 confirms the Servlet API is not bundled.
  • If this prints 1, a dependency pulled the API in with compile scope. Change it to provided, or exclude it from the library that brings it.

Real-World Example: Build WAR File in Java for a Versioned Release

This release build produces student-portal##002.war. Tomcat's parallel deployment keeps version 001 running for users who are already logged in, while new sessions go to version 002. The app also shows its version on a status page.

<!-- pom.xml (only the parts that change) -->
<version>2.0.0</version>
<packaging>war</packaging>

<properties>
  <maven.compiler.release>21</maven.compiler.release>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <deploy.version>002</deploy.version>
</properties>

<build>
  <finalName>student-portal##${deploy.version}</finalName>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>   <!-- replaces ${...} in resource files -->
    </resource>
  </resources>
  <plugins>
    <plugin>
      <artifactId>maven-war-plugin</artifactId>
      <version>3.4.0</version>
      <configuration>
        <archive>
          <manifestEntries>
            <Implementation-Version>${project.version}</Implementation-Version>
          </manifestEntries>
        </archive>
      </configuration>
    </plugin>
  </plugins>
</build>
# src/main/resources/build.properties
app.version=${project.version}
deploy.label=${deploy.version}
// src/main/java/com/gocourse/portal/StatusServlet.java
package com.gocourse.portal;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@WebServlet("/status")
public class StatusServlet extends HttpServlet {

    private final Properties buildInfo = new Properties();

    @Override
    public void init() throws ServletException {
        // build.properties is inside WEB-INF/classes, so the class loader finds it
        try (InputStream input = getClass().getResourceAsStream("/build.properties")) {
            if (input == null) {
                throw new ServletException("build.properties is missing from the WAR");
            }
            buildInfo.load(input);
        } catch (IOException e) {
            throw new ServletException("Cannot read build.properties", e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().printf(
                "{\"app\":\"student-portal\",\"version\":\"%s\",\"deploy\":\"%s\",\"context\":\"%s\"}%n",
                buildInfo.getProperty("app.version"),
                buildInfo.getProperty("deploy.label"),
                request.getContextPath());
    }
}

Build, check and deploy next to the running version:

mvn -q package
jar tf "target/student-portal##002.war" | grep -E "build.properties|lib/|Status"
cp "target/student-portal##002.war" $CATALINA_HOME/webapps/
ls $CATALINA_HOME/webapps
curl -s http://localhost:8080/student-portal/status

Output:

WEB-INF/classes/build.properties
WEB-INF/classes/com/gocourse/portal/StatusServlet.class
WEB-INF/lib/gson-2.13.2.jar
WEB-INF/lib/error_prone_annotations-2.41.0.jar
ROOT  student-portal##001  student-portal##001.war  student-portal##002  student-portal##002.war
{"app":"student-portal","version":"2.0.0","deploy":"002","context":"/student-portal"}

How it works:

  1. Versioned file name. finalName adds ##002. Tomcat deploys it beside ##001 under the same /student-portal path. The quotes around the file name stop the shell from treating # as a comment.
  2. Sessions stay safe. Requests that carry a session from version 001 keep going to 001. New visitors reach 002. Once no sessions use 001, you delete student-portal##001.war.
  3. One source of truth. Resource filtering copies project.version and deploy.version into build.properties, which ends up in WEB-INF/classes. The status page always matches the build.
  4. Fail fast. init() throws ServletException if the file is missing, so a broken WAR fails at deployment instead of on a user's request. How init() fits into a servlet's life is covered in Servlet Lifecycle in Java.
  5. Clean contents. The jar tf check confirms the version file, the servlet and the Gson library are inside, with no Servlet API JAR.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Build WAR File in Java and get answers drawn from it.

Signed-in readers only.