Build WAR File in Java
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 WAR | Contains | Visible to browsers? |
|---|---|---|
/ (root) | HTML, CSS, JavaScript, images, JSP files | Yes |
/WEB-INF/classes/ | Your compiled .class files and resources | No |
/WEB-INF/lib/ | Library JARs your app needs at run time | No |
/WEB-INF/web.xml | Optional deployment descriptor (servlet mappings, welcome files) | No |
/META-INF/MANIFEST.MF | Archive metadata | No |
JAR vs WAR
| JAR | WAR | |
|---|---|---|
| Started by | java -jar app.jar | A servlet container (Tomcat, Jetty, GlassFish) |
Needs main method | Yes, for executable JARs | No |
| Libraries | Unpacked (fat JAR) or in lib/ next to it | Inside WEB-INF/lib |
| Servlet API | Must be bundled if used | Supplied by the container |
How it works:
- Anything under
WEB-INFis private. A request for/WEB-INF/web.xmlreturns404, 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, soweb.xmlis not required.- The
jakarta.servletpackages come from the Servlet API. Tomcat 10 and later usejakarta.*; very old tutorials usejavax.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=warswitches thepackagephase from the JAR plugin to the WAR plugin, which buildstarget/student-portal.war.finalNamedrops the version from the file name. The file name becomes the URL path in Tomcat, sostudent-portal.waris served at/student-portal.- Compiled classes go to
WEB-INF/classes, and everything insrc/main/webappis copied to the WAR root. WEB-INF/libis missing because the only dependency isprovided.
Note: Since version 3.0 the WAR plugin no longer fails when
web.xmlis missing. Annotation-only apps can deletesrc/main/webapp/WEB-INF/web.xmlcompletely.
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 scope | Gradle configuration | On compile classpath | Inside WEB-INF/lib |
|---|---|---|---|
compile | implementation | Yes | Yes |
runtime | runtimeOnly | No | Yes |
provided | providedCompile | Yes | No |
test | testImplementation | Tests only | No |
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
compilescope, so it and its transitive dependency are copied intoWEB-INF/lib. - The Servlet API JAR is not there, because Tomcat provides
jakarta.servlet-apiitself. Two copies of the same API on one class path can cause confusingClassCastExceptionandLinkageErrorproblems. - 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
warplugin applies thejavaplugin too, sosrc/main/javais compiled as usual. providedCompileis Gradle's equivalent of Maven'sprovidedscope../gradlew buildalso runswar, because the plugin makesassembledepend on it.archiveFileNamecontrols the output name inbuild/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 underWEB-INF, where browsers cannot reach them but your code can read them withgetServletContext().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
webappsevery few seconds (autoDeploy). It unpacksstudent-portal.warinto astudent-portal/folder and starts the app. - The context path comes from the file name:
student-portal.waris served at/student-portal, andROOT.waris 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 name | URL |
|---|---|
student-portal.war | http://localhost:8080/student-portal/ |
ROOT.war | http://localhost:8080/ |
api#v1.war | http://localhost:8080/api/v1/ |
shop##003.war | http://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.
| Command | What it shows |
|---|---|
jar tf app.war | Every entry in the archive |
jar tf app.war | grep WEB-INF/lib | Bundled libraries |
unzip -p app.war WEB-INF/web.xml | The deployment descriptor |
mvn dependency:tree -Dscope=runtime | Why a library was included (Maven) |
./gradlew dependencies --configuration runtimeClasspath | The same for Gradle |
jar tf target/student-portal.war | grep -c "servlet-api"
Output:
0
How it works:
grep -ccounts matching lines.0confirms the Servlet API is not bundled.- If this prints
1, a dependency pulled the API in withcompilescope. Change it toprovided, 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:
- Versioned file name.
finalNameadds##002. Tomcat deploys it beside##001under the same/student-portalpath. The quotes around the file name stop the shell from treating#as a comment. - 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. - One source of truth. Resource filtering copies
project.versionanddeploy.versionintobuild.properties, which ends up inWEB-INF/classes. The status page always matches the build. - Fail fast.
init()throwsServletExceptionif the file is missing, so a broken WAR fails at deployment instead of on a user's request. Howinit()fits into a servlet's life is covered in Servlet Lifecycle in Java. - Clean contents. The
jar tfcheck confirms the version file, the servlet and the Gson library are inside, with no Servlet API JAR.