Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 37 ยท Getting Started

Your First Tomcat Web Application

Build and deploy a first Tomcat web application: project layout, a servlet, web.xml, packaging a WAR, deploying it and reading the URL, with runnable WAR stand-ins.

The fastest way to understand Tomcat is to deploy something. A Tomcat web application is just a directory tree with a fixed structure, usually zipped into a .war (Web Application Archive) file. In this lesson you create the smallest useful app, look at every file, package it, and see how the URL you type maps to the files on disk.

Because Tomcat itself does not run on this site, the servlet, web.xml and shell commands are shown read-only. The runnable programs build a real WAR file in memory with the JDK's java.util.zip classes and inspect it, which is exactly what the jar tool does.

The standard structure

Every web app follows the same layout, whether you build it with Maven, Gradle or by hand:

TEXT
hello/
  index.html                 public file, served as /hello/ (welcome file)
  css/site.css               public static resource
  WEB-INF/                   private: never served to browsers
    web.xml                  deployment descriptor (optional with annotations)
    classes/                 compiled .class files and resources
      com/example/HelloServlet.class
    lib/                     JAR libraries used by this app only

The WEB-INF folder is special. Tomcat refuses to serve anything inside it, so it is the right place for configuration, compiled code, JSP fragments you do not want to expose and libraries. Everything outside WEB-INF is public and served as a file, unless a servlet is mapped to that URL.

Anatomy of a WAR

Public files HTML, CSS, images, JSP
WEB-INF Never served to browsers
classes Your compiled code
lib Your JAR libraries

The folder name hello becomes the URL /hello.

1 / 2

Step 1: a servlet

This servlet answers GET requests and greets the name in the query string. It uses the jakarta.* imports of Tomcat 10 and later.

Java
package com.example;

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(name = "hello", urlPatterns = "/greet")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        if (name == null || name.isBlank()) {
            name = "world";
        }
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().println("<h1>Hello, " + escape(name) + "!</h1>");
    }

    private static String escape(String s) {
        return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
    }
}

Never write user input into HTML without escaping it, as the escape helper does here; otherwise you create a cross-site scripting hole.

Step 2: the deployment descriptor

With @WebServlet you do not need a web.xml, but many teams still ship one for settings such as welcome files and session timeout:

XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
                             https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
         version="6.0">
  <display-name>Hello</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
</web-app>

Step 3: compile and package

With plain command-line tools (assuming Tomcat's lib/servlet-api.jar for the compiler):

Terminal
mkdir -p build/WEB-INF/classes
javac -cp "$CATALINA_HOME/lib/servlet-api.jar" -d build/WEB-INF/classes src/com/example/HelloServlet.java
cp web/index.html build/
cp web/WEB-INF/web.xml build/WEB-INF/
cd build && jar cvf ../hello.war .

In a real project you let Maven do it: set <packaging>war</packaging>, mark the servlet API as provided (the container supplies it, so it must not be inside your WAR) and run mvn package.

The program below builds a WAR the same way (a WAR is a ZIP file) and lists its entries. It also checks the two classic mistakes: a missing WEB-INF/web.xml is allowed, but servlet API classes bundled inside WEB-INF/lib are a warning.

Java Build and inspect a WAR in memory (stand-in for the jar tool)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Step 4: deploy and visit

Copy hello.war into Tomcat's webapps directory. A running Tomcat notices the new file, unpacks it into webapps/hello/ and starts the application; the log shows a line like Deployment of web application archive [...hello.war] has finished. The URL is built from four pieces:

TEXT
http://localhost:8080/hello/greet?name=Ada
        host   port  context servlet  query
  • Context path /hello comes from the file name hello.war.
  • Servlet path /greet comes from urlPatterns.
  • Query string name=Ada is read with getParameter.

This stand-in resolves a URL against the WAR's structure the way Tomcat conceptually does: first the context, then servlet mappings, then static files, then 404.

Java Resolving a URL against an application (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The redirect from /hello to /hello/ is real Tomcat behavior for directory-like URLs; the stand-in only imitates it.

Common first-time problems

  • 404 on the context: the WAR did not deploy. Look in logs/catalina.*.log and logs/localhost.*.log for a stack trace (the track page lists the troubleshooting chapter).
  • ClassNotFoundException: javax.servlet...: your code targets the wrong namespace for your Tomcat (versions lesson).
  • Duplicate servlet API: never bundle servlet-api.jar in WEB-INF/lib; keep it provided.
  • Changes not visible: after rebuilding, redeploy the WAR; Tomcat does not watch your source tree.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is special about the WEB-INF folder?

    WEB-INF holds private configuration, classes and libraries. A request for /app/WEB-INF/web.xml returns 404.
  2. 2. A file is deployed as shop.war. What is its default context path?

    The WAR file name without .war becomes the context path (ROOT.war is the special case that maps to /).
  3. 3. In a Maven project, how should the servlet API dependency be declared?

    Tomcat already contains the servlet API. Bundling a second copy can cause class loading conflicts.
  4. 4. Is a web.xml file required when you use @WebServlet?

    Since Servlet 3.0, web.xml is optional. You still need it for some settings or to override annotations.

Summary

  • A web app is a folder (or WAR) with public files plus a private WEB-INF containing web.xml, classes and lib.
  • Servlets are mapped with @WebServlet or in web.xml; use jakarta.* imports on Tomcat 10 and later.
  • A WAR is a ZIP file; build it with jar or your build tool, keeping the servlet API provided.
  • Copy it into webapps: the file name gives the context path.
  • The URL is host, port, context path, servlet path and query string.

Next: Tomcat compared with other servers