Java Web Application
A Java web application is a set of servlets, filters, listeners, JSP pages and static files that a servlet container such as Tomcat runs together under one URL path. Each piece has one job: servlets handle requests, JSP pages render HTML, filters run code before every request, and listeners react to the application starting and stopping. Packaged as a WAR file, the whole Java web application can be deployed to any Jakarta EE compatible server.
This lesson builds a complete Study Planner web application step by step on Tomcat 11 (Jakarta Servlet 6.1, Jakarta Pages 4.0, Jakarta Expression Language 6.0). Users log in with a name, add study tasks, mark them done and log out.
Parts of a Java Web Application
| Part | Annotation / file | Job |
|---|---|---|
| Servlet | @WebServlet | Receives a request and decides what to do (controller) |
| JSP page | *.jsp | Renders HTML from data (view) |
| Filter | @WebFilter | Runs before servlets, for login checks, logging, encoding |
| Listener | @WebListener | Runs code when the app starts or stops, or when sessions change |
HttpSession | request.getSession() | Remembers one user between requests |
ServletContext | getServletContext() | Shared storage for the whole application |
web.xml | WEB-INF/web.xml | Optional settings: welcome file, error pages, session timeout |
| Static files | css/, js/, images | Served directly by the container |
How it works:
- The container creates one
ServletContextper application and one instance of each servlet and filter. Many threads use these instances at the same time, so shared data must be thread-safe. - A browser request travels through the matching filters, then reaches a servlet, which usually forwards to a JSP to build the HTML. The Java Servlet lesson explains a single servlet; this lesson connects all the parts.
Java Web Application Folder Structure
A Maven web project and the WAR it produces use two related layouts.
studyplanner/ (Maven project)
├── pom.xml
└── src/main/
├── java/com/gocourse/planner/
│ ├── TaskStore.java
│ ├── AppStartupListener.java
│ ├── AuthFilter.java
│ ├── LoginServlet.java
│ ├── LogoutServlet.java
│ └── TaskServlet.java
└── webapp/
├── index.jsp
├── css/style.css
└── WEB-INF/
├── web.xml
└── views/
├── login.jsp
├── tasks.jsp
└── 404.jsp
studyplanner.war (what Tomcat deploys)
├── index.jsp
├── css/style.css
└── WEB-INF/
├── web.xml
├── views/*.jsp
├── classes/com/gocourse/planner/*.class
└── lib/*.jar
How it works:
- Everything in
src/main/webappis copied to the root of the WAR, and compiled classes go toWEB-INF/classes. - Files under
WEB-INFcan never be requested directly by a browser. Putting JSP views there forces every page to go through a servlet first, so no one can skip the login check by typing a JSP URL.
Configure the pom.xml
<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>studyplanner</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>
<!-- Supplied by Tomcat at runtime -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.1.0</version>
<scope>provided</scope>
</dependency>
<!-- JSTL is NOT included in Tomcat, so it goes into WEB-INF/lib -->
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
<build>
<finalName>studyplanner</finalName>
</build>
</project>
How it works:
<packaging>war</packaging>tells Maven to buildtarget/studyplanner.warinstead of a JAR.- The Servlet API uses
providedscope because Tomcat already contains it. Bundling a second copy causes class loading errors. <finalName>sets the WAR name, and Tomcat uses the WAR name as the context path:studyplanner.waris served at/studyplanner. The Build WAR File in Java lesson covers packaging in more detail.
Shared Data With a Thread-Safe Store
The application needs somewhere to keep tasks. This lesson uses an in-memory store; a real application would call a database through JDBC or JPA.
package com.gocourse.planner;
import java.util.ArrayList;
import java.util.List;
public class TaskStore {
public record Task(int id, String owner, String title, boolean done) {}
private final List<Task> tasks = new ArrayList<>();
private int nextId = 1;
public synchronized Task add(String owner, String title) {
Task task = new Task(nextId++, owner, title, false);
tasks.add(task);
return task;
}
public synchronized List<Task> forOwner(String owner) {
return tasks.stream().filter(task -> task.owner().equals(owner)).toList();
}
public synchronized boolean complete(int id, String owner) {
for (int i = 0; i < tasks.size(); i++) {
Task task = tasks.get(i);
if (task.id() == id && task.owner().equals(owner)) {
tasks.set(i, new Task(task.id(), task.owner(), task.title(), true));
return true;
}
}
return false;
}
}
How it works:
- Every method is
synchronizedbecause Tomcat serves requests on many threads at once. Without locking, two users adding tasks together could receive the same id. forOwnerreturns an unmodifiable copy (toList()), so a JSP looping over it never sees the list change halfway through.completechecks the owner as well as the id, so one user cannot complete another user's task by guessing an id.
Start the Application With a ServletContextListener
A ServletContextListener runs once when the Java web application starts and once when it stops. It is the right place to create shared objects.
package com.gocourse.planner;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
@WebListener
public class AppStartupListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext context = event.getServletContext();
context.setAttribute("taskStore", new TaskStore());
context.log("Study Planner started at " + context.getContextPath());
}
@Override
public void contextDestroyed(ServletContextEvent event) {
event.getServletContext().log("Study Planner stopped");
}
}
Tomcat log (logs/localhost.<date>.log):
INFO [main] org.apache.catalina.core.ApplicationContext.log Study Planner started at /studyplanner
How it works:
@WebListenerregisters the class automatically; noweb.xmlentry is needed.setAttribute("taskStore", ...)stores oneTaskStorein the application scope. Every servlet can read it withgetServletContext().getAttribute("taskStore").contextDestroyedruns on shutdown or redeploy. Close connection pools and stop background threads here.
Handle Login With a Servlet and HttpSession
LoginServlet shows the login form on GET and starts a session on POST.
package com.gocourse.planner;
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 jakarta.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
if (name == null || name.isBlank()) {
request.setAttribute("error", "Please enter your name.");
request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
return;
}
// Throw away any old session to prevent session fixation, then start a fresh one
HttpSession oldSession = request.getSession(false);
if (oldSession != null) {
oldSession.invalidate();
}
HttpSession session = request.getSession(true);
session.setAttribute("user", name.strip());
response.sendRedirect(request.getContextPath() + "/app/tasks");
}
}
<%-- src/main/webapp/WEB-INF/views/login.jsp --%>
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Study Planner - Login</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css">
</head>
<body>
<h1>Study Planner</h1>
<p class="error">${error}</p>
<form method="post" action="${pageContext.request.contextPath}/login">
<label>Your name <input name="name"></label>
<button>Log in</button>
</form>
</body>
</html>
curl -i -c cookies.txt -d "name=Asha" http://localhost:8080/studyplanner/login
Output:
HTTP/1.1 302
Set-Cookie: JSESSIONID=5C1F0A8E2B7D41F39A6C2E8D0B4A7F31; Path=/studyplanner; HttpOnly
Location: /studyplanner/app/tasks
Content-Length: 0
How it works:
getSession(true)creates a session and Tomcat sends its id in theJSESSIONIDcookie. The browser returns that cookie on every later request, so the server knows it is still Asha.- Invalidating the old session before logging in gives the user a new session id, which blocks session fixation attacks.
sendRedirectanswers with302and aLocationheader. Always prefix paths withgetContextPath()so the app works under any context path.
Note: This lesson accepts any name to keep the focus on the web application structure. Real logins check a password hash, as shown in the Password Hashing lesson.
Protect Pages With a Filter
Instead of checking the session in every servlet, one filter guards every URL under /app/.
package com.gocourse.planner;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/app/*")
public class AuthFilter extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession(false);
boolean loggedIn = session != null && session.getAttribute("user") != null;
if (loggedIn) {
chain.doFilter(request, response); // continue to the servlet
} else {
response.sendRedirect(request.getContextPath() + "/login");
}
}
}
curl -i http://localhost:8080/studyplanner/app/tasks
Output:
HTTP/1.1 302
Location: /studyplanner/login
Content-Length: 0
How it works:
@WebFilter("/app/*")runs this filter before every request whose path starts with/app/.getSession(false)returnsnullinstead of creating an empty session for anonymous visitors.- Calling
chain.doFilterpasses the request on. Not calling it stops the request, and the redirect sends the visitor to the login page. HttpFilteris the HTTP-specific base class, so there is no need to castServletRequesttoHttpServletRequest.
Controller Servlet and JSP View for Tasks
TaskServlet is the main controller. GET shows the list; POST adds or completes a task and then redirects.
package com.gocourse.planner;
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;
@WebServlet("/app/tasks")
public class TaskServlet extends HttpServlet {
private TaskStore store;
@Override
public void init() {
store = (TaskStore) getServletContext().getAttribute("taskStore");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user = (String) request.getSession().getAttribute("user");
request.setAttribute("tasks", store.forOwner(user));
request.getRequestDispatcher("/WEB-INF/views/tasks.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String user = (String) request.getSession().getAttribute("user");
String action = request.getParameter("action");
if ("add".equals(action)) {
String title = request.getParameter("title");
if (title != null && !title.isBlank()) {
store.add(user, title.strip());
}
} else if ("complete".equals(action)) {
try {
store.complete(Integer.parseInt(request.getParameter("id")), user);
} catch (NumberFormatException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid task id");
return;
}
}
// Post/Redirect/Get: a browser refresh repeats the GET, not the POST
response.sendRedirect(request.getContextPath() + "/app/tasks");
}
}
<%-- src/main/webapp/WEB-INF/views/tasks.jsp --%>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<!DOCTYPE html>
<html>
<head><title>My Study Tasks</title></head>
<body>
<h1>Hello, <c:out value="${sessionScope.user}"/></h1>
<form method="post">
<input type="hidden" name="action" value="add">
<input name="title" placeholder="New task">
<button>Add</button>
</form>
<ul>
<c:forEach var="task" items="${tasks}">
<li>
<c:out value="${task.title}"/>
<c:choose>
<c:when test="${task.done}">(done)</c:when>
<c:otherwise>
<form method="post" style="display:inline">
<input type="hidden" name="action" value="complete">
<input type="hidden" name="id" value="${task.id}">
<button>Mark done</button>
</form>
</c:otherwise>
</c:choose>
</li>
</c:forEach>
</ul>
<p>${tasks.size()} task(s) - <a href="${pageContext.request.contextPath}/logout">Log out</a></p>
</body>
</html>
curl -s -b cookies.txt -d "action=add&title=Revise JDBC" http://localhost:8080/studyplanner/app/tasks
curl -s -b cookies.txt -d "action=add&title=Read JSP lesson" http://localhost:8080/studyplanner/app/tasks
curl -s -b cookies.txt -d "action=complete&id=1" http://localhost:8080/studyplanner/app/tasks
curl -s -b cookies.txt http://localhost:8080/studyplanner/app/tasks
Output (HTML of the last request, whitespace trimmed):
<h1>Hello, Asha</h1>
...
<li>Revise JDBC (done)</li>
<li>Read JSP lesson <form method="post" ...><button>Mark done</button></form></li>
</ul>
<p>2 task(s) - <a href="/studyplanner/logout">Log out</a></p>
How it works:
init()runs once when Tomcat creates the servlet and reads theTaskStorethe listener created, so every request shares one store.- The servlet puts data into the request with
setAttribute("tasks", ...)and forwards to the JSP. This is the MVC pattern: servlet = controller,TaskStore= model, JSP = view. ${task.title}reads a record component directly. Jakarta Expression Language 6.0 (Tomcat 11) supports records; older containers need classic getters.<c:out>escapes HTML, so a task titled<script>is shown as text instead of running. Use it for every value a user typed. See JSP in Java for the EL and JSTL details.- After every
POSTthe servlet redirects. If the user presses refresh, the browser repeats the harmlessGETinstead of adding the task twice.
Log Out by Invalidating the Session
package com.gocourse.planner;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate(); // removes "user" and every other session attribute
}
response.sendRedirect(request.getContextPath() + "/login");
}
}
curl -i -b cookies.txt http://localhost:8080/studyplanner/logout
curl -i -b cookies.txt http://localhost:8080/studyplanner/app/tasks
Output:
HTTP/1.1 302
Location: /studyplanner/login
HTTP/1.1 302
Location: /studyplanner/login
How it works:
- After
invalidate(), the oldJSESSIONIDno longer matches any session on the server. - The second request still sends the old cookie, but
AuthFilterfinds no session and redirects to the login page. The tasks stay inTaskStoreand reappear when Asha logs in again.
Configure Error Pages and Sessions in web.xml
Annotations cover servlets, filters and listeners. Application-wide settings still live in WEB-INF/web.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_1.xsd"
version="6.1">
<display-name>Study Planner</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>30</session-timeout> <!-- minutes of inactivity -->
<cookie-config>
<http-only>true</http-only>
</cookie-config>
</session-config>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/views/404.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/WEB-INF/views/error.jsp</location>
</error-page>
</web-app>
<%-- src/main/webapp/index.jsp --%>
<% response.sendRedirect(request.getContextPath() + "/app/tasks"); %>
curl -i http://localhost:8080/studyplanner/no-such-page
Output:
HTTP/1.1 404
Content-Type: text/html;charset=UTF-8
<h1>Page not found</h1>
How it works:
version="6.1"matches Jakarta Servlet 6.1 in Tomcat 11. Annotations andweb.xmlwork together, andweb.xmlwins if both configure the same thing.- The welcome file makes
/studyplanner/openindex.jsp, which redirects to the task list (and the filter sends anonymous users on to the login page). - Error pages replace Tomcat's default error screen, which shows the server version and stack traces to visitors. The status code stays
404, so browsers and search engines still see the real result.
Build and Deploy the Java Web Application to Tomcat
# 1. Build the WAR
mvn clean package
# 2. Copy it into Tomcat's webapps folder (Tomcat unpacks and starts it)
cp target/studyplanner.war $CATALINA_HOME/webapps/
# 3. Start Tomcat if it is not running
$CATALINA_HOME/bin/startup.sh # Windows: bin\startup.bat
# 4. Open the app
curl -i http://localhost:8080/studyplanner/
Output:
[INFO] Building war: /home/asha/studyplanner/target/studyplanner.war
[INFO] BUILD SUCCESS
...
HTTP/1.1 302
Location: /studyplanner/app/tasks
How it works:
- Tomcat watches
webapps. A new or updated WAR is deployed automatically, and the context path comes from the file name. - To serve the app at the site root (
http://localhost:8080/), name the fileROOT.war. - Redeploying restarts the application:
contextDestroyedruns, thencontextInitializedruns again, and in-memory data is lost. That is why production applications keep data in a database.
Real-World Example: Request Timing and Active Users in the Java Web Application
Operations teams want two numbers from every web app: how slow each page is and how many users are online. A filter and a session listener add both without touching the existing servlets.
package com.gocourse.planner;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class TimingFilter extends HttpFilter {
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
long start = System.nanoTime();
try {
chain.doFilter(request, response);
} finally {
long millis = (System.nanoTime() - start) / 1_000_000;
getServletContext().log("%s %s -> %d in %d ms".formatted(
request.getMethod(), request.getRequestURI(), response.getStatus(), millis));
}
}
}
package com.gocourse.planner;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import java.util.concurrent.atomic.AtomicInteger;
@WebListener
public class ActiveUserListener implements HttpSessionListener {
private static final AtomicInteger ACTIVE_SESSIONS = new AtomicInteger();
@Override
public void sessionCreated(HttpSessionEvent event) {
int now = ACTIVE_SESSIONS.incrementAndGet();
event.getSession().getServletContext().setAttribute("activeUsers", now);
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
int now = ACTIVE_SESSIONS.decrementAndGet();
event.getSession().getServletContext().setAttribute("activeUsers", now);
}
}
Add one line to tasks.jsp:
<p>Users online: ${applicationScope.activeUsers}</p>
curl -s -c asha.txt -d "name=Asha" http://localhost:8080/studyplanner/login
curl -s -c ravi.txt -d "name=Ravi" http://localhost:8080/studyplanner/login
curl -s -b ravi.txt http://localhost:8080/studyplanner/app/tasks | grep online
curl -s -b asha.txt http://localhost:8080/studyplanner/logout
curl -s -b ravi.txt http://localhost:8080/studyplanner/app/tasks | grep online
Output (page) and Tomcat log:
<p>Users online: 2</p>
<p>Users online: 1</p>
POST /studyplanner/login -> 302 in 3 ms
POST /studyplanner/login -> 302 in 1 ms
GET /studyplanner/app/tasks -> 200 in 14 ms
GET /studyplanner/logout -> 302 in 0 ms
GET /studyplanner/app/tasks -> 200 in 2 ms
How it works:
- Filter order.
TimingFiltermaps to/*, so it wraps every request, including the onesAuthFilterhandles. Thefinallyblock logs even when a servlet throws an exception, andgetStatus()reports the final status code. - Forwarded requests. The forward from
TaskServlettotasks.jspis not timed twice. Filters run only for the original request unless they are mapped with theFORWARDdispatcher type. - Session events. Tomcat calls
sessionCreatedwhengetSession(true)makes a session andsessionDestroyedwhen a session is invalidated or times out after 30 minutes. - Thread-safe counter. Sessions are created on many threads at once, so the count uses
AtomicIntegerinstead of a plainint. - Application scope in JSP.
${applicationScope.activeUsers}reads theServletContextattribute, the same storage the startup listener used forTaskStore. Every part of the Java web application, from filters to listeners to JSP pages, shares data through these three scopes: request, session and application. Reading the incoming data in more depth is covered in HttpServletRequest in Java.