Deploying Servlets on Apache Tomcat
Course: Advanced Java Training
Topic: Deploying Servlets on Apache Tomcat
Course Link: Advanced Java Training Course
Demo Link: Register for a Course Demo
JustAcademy Homepage: Visit JustAcademy
1. Introduction to Servlet Deployment
Servlet deployment is the process of packaging, installing, configuring, and running a Java servlet-based web application on a servlet container. A servlet is a Java class that processes HTTP requests and generates responses. It requires a compatible servlet container to manage its lifecycle and handle incoming requests.
Apache Tomcat is an open-source Java web server and servlet container that supports Jakarta Servlet and related web technologies. It receives HTTP requests, identifies the target web application, invokes the appropriate servlet, and returns the response to the client.
During development, a servlet may be executed directly through an IDE's configured Tomcat server. For distribution, a web application is commonly packaged as a WAR file and deployed to a Tomcat installation.
2. Learning Objectives
- Understand Apache Tomcat and its role in servlet deployment.
- Install and configure a compatible Java Development Kit and Tomcat server.
- Understand the standard Java web application directory structure.
- Create a servlet and map it to a URL.
- Configure a servlet using annotations or
web.xml.
- Build a web application and package it as a WAR file.
- Deploy an application using the Tomcat
webapps directory.
- Test deployed servlets in a web browser.
- Identify common deployment errors and resolve them.
- Apply basic deployment and security best practices.
3. What Is Apache Tomcat?
Apache Tomcat is a servlet container that provides the runtime environment required to execute Java web applications. It implements relevant Jakarta Servlet specifications and manages servlet initialization, request handling, session management, and destruction.
Key Features of Tomcat
- Servlet container: Loads and executes servlet classes.
- HTTP connector: Accepts HTTP connections on configured ports.
- Application deployment: Deploys web applications from directories or WAR archives.
- Session management: Supports HTTP sessions for maintaining user-specific state.
- Configuration: Provides server and application configuration options.
- Logging: Records server events and application errors.
- Management: Provides tools for managing deployed applications when configured appropriately.
4. Understanding the Servlet Deployment Architecture
A typical servlet application follows this request-processing flow:
- The user enters an application URL in a browser.
- The browser sends an HTTP request to the Tomcat server.
- Tomcat identifies the target application using its context path.
- The servlet container matches the request URL to the appropriate servlet mapping.
- The container invokes the servlet's relevant handler, such as
doGet() or doPost().
- The servlet processes the request and prepares an HTTP response.
- Tomcat sends the response to the browser.
Important Components
| Component |
Description |
| Browser |
Sends requests and displays responses. |
| Tomcat server |
Accepts connections and hosts web applications. |
| Servlet container |
Manages servlet lifecycle and request dispatching. |
| Servlet class |
Contains Java code that handles requests. |
| URL mapping |
Connects a request path to a servlet. |
| WAR file |
Packages a web application for deployment. |
| Deployment descriptor |
The optional or required-by-configuration web.xml file that defines application configuration. |
5. Prerequisites for Deploying Servlets
Before deploying a servlet, ensure that the following software and resources are available.
- Java Development Kit (JDK): Provides the Java compiler and runtime tools.
- Apache Tomcat: Runs the servlet application.
- IDE or text editor: Such as Eclipse, IntelliJ IDEA, or Visual Studio Code with suitable Java extensions.
- Build tool: Maven or Gradle is useful for dependency management and WAR packaging.
- Web browser: Used to test the application.
Always select a Tomcat version compatible with your Java version and the Servlet API used by the application. Tomcat 10 and later use the jakarta.servlet namespace, while older applications targeting Tomcat 9 commonly use javax.servlet.
6. Installing and Configuring Apache Tomcat
Step 1: Install Java
Install a JDK that is supported by your selected Tomcat version. Verify the installation from a terminal or command prompt.
java -version
javac -version
If the commands are not recognized, configure the system's Java installation and PATH settings as appropriate.
Step 2: Download Tomcat
Download a compatible Tomcat distribution from the official Apache website:
Apache Tomcat Official Website
Choose the version that matches your application's Servlet API and Java requirements. Extract the downloaded archive into a suitable directory.
Step 3: Identify the Tomcat Directories
| Directory |
Purpose |
bin |
Contains startup and shutdown scripts. |
conf |
Contains server configuration files, including server.xml. |
logs |
Contains server and application-related logs. |
webapps |
Default deployment location for web applications. |
lib |
Contains libraries used by Tomcat itself. |
work |
Contains generated working files used by the server. |
Step 4: Start Tomcat
On Windows, open Command Prompt, navigate to the Tomcat bin directory, and run:
startup.bat
On Linux or macOS, run:
./startup.sh
Check the startup logs if the server does not start. By default, Tomcat commonly listens on port 8080, unless its connector configuration has been changed.
Step 5: Verify the Server
Open the following address in a browser:
http://localhost:8080/
If Tomcat is running and its default application is available, the Tomcat landing page or configured root application should appear.
7. Understanding the Java Web Application Structure
A traditional Java web application uses a standard directory structure. Tomcat can deploy an unpacked application directory or a packaged WAR archive.
MyServletApp/
├── src/
│ └── main/
│ ├── java/
│ │ └── com/
│ │ └── example/
│ │ └── HelloServlet.java
│ ├── resources/
│ └── webapp/
│ ├── index.html
│ └── WEB-INF/
│ └── web.xml
└── pom.xml
In a Maven project, Java source files are compiled into class files under the build output directory. When the WAR is created, the compiled classes and web resources are packaged into the correct locations.
Important Deployment Locations
index.html provides a static entry page for the application.
WEB-INF/web.xml contains deployment configuration when used.
WEB-INF/classes/ contains compiled application classes and resources.
WEB-INF/lib/ contains application libraries packaged with the web application.
Resources inside WEB-INF are not directly accessible through ordinary browser URLs. They are intended for server-side use.
8. Creating a Servlet for Deployment
Create a servlet class that extends HttpServlet. The following example uses Jakarta Servlet imports and the annotation-based mapping approach.
Example: HelloServlet.java
package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head><title>Hello Servlet</title></head>");
out.println("<body>");
out.println("<h1>Hello from Apache Tomcat!</h1>");
out.println("<p>The servlet has been deployed successfully.</p>");
out.println("</body>");
out.println("</html>");
}
}
Code Explanation
package com.example; defines the Java package for the servlet.
extends HttpServlet makes the class an HTTP servlet.
@WebServlet("/hello") maps the servlet to the /hello path.
doGet() processes HTTP GET requests.
setContentType() specifies that the response is HTML encoded in UTF-8.
getWriter() obtains a writer for the response body.
9. Configuring a Servlet Using web.xml
Instead of annotations, an application can configure servlet classes and URL mappings in WEB-INF/web.xml. This is useful when a project uses centralized deployment configuration.
<?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">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
This descriptor uses Servlet 6.0 configuration. Ensure the deployed Tomcat version supports the declared specification. If using annotation-based mapping, the corresponding mapping usually does not need to be repeated in web.xml.
10. Building a WAR File with Maven
A WAR (Web Application Archive) file packages the application into a format suitable for deployment. Maven can compile Java code, resolve dependencies, and create a WAR archive.
Example 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.example</groupId>
<artifactId>MyServletApp</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
Note: The example targets Servlet 6.0 and Java 17. Confirm that your chosen Tomcat version supports these requirements. The provided scope is used because the servlet container supplies the Servlet API at runtime.
Build the Project
Open a terminal in the directory containing pom.xml and execute:
mvn clean package
If the build succeeds, Maven creates a WAR file in the target directory, commonly named:
target/MyServletApp-1.0.0.war
The precise filename depends on the project's artifact ID and version.
11. Deploying the WAR File on Tomcat
One of the simplest deployment methods is copying the WAR file into Tomcat's configured application base directory. In a standard installation, this directory is commonly named webapps.
Deployment Steps
- Build the project and locate the generated WAR file.
- Locate the Tomcat installation directory.
- Open the
webapps directory.
- Copy the WAR file into that directory.
- Start Tomcat, or allow its configured auto-deployment mechanism to detect the new WAR.
- Review the logs to confirm that deployment completed successfully.
- Open the servlet URL in the browser.
If the file is named MyServletApp-1.0.0.war, Tomcat commonly uses /MyServletApp-1.0.0 as the application context path.
Example servlet URL:
http://localhost:8080/MyServletApp-1.0.0/hello
The context path depends on the deployed application name and any explicit context configuration.
12. Deploying an Unpacked Application Directory
Tomcat can also deploy an unpacked web application directory when the host configuration permits it. The directory must follow the expected web application structure.
For example, if the application directory is named MyServletApp, it may be placed at:
TOMCAT_HOME/webapps/MyServletApp/
Its structure should include the web resources and a WEB-INF directory containing compiled classes and required libraries. A build tool is recommended to ensure that the application is assembled correctly.
13. Deploying Through the Tomcat Manager
The Tomcat Manager web application can deploy, reload, stop, start, and undeploy applications. Access to Manager must be configured carefully and restricted to authorized administrators.
General Procedure
- Start Tomcat and confirm that the Manager application is installed.
- Configure an authorized Manager user according to Tomcat's documentation.
- Open the Manager interface at the appropriate Manager URL, commonly
http://localhost:8080/manager/html.
- Authenticate with an authorized account.
- Use the deployment controls to deploy the WAR file or manage an existing application.
- Check the deployment status and review logs if an error occurs.
Do not expose the Manager application publicly without appropriate access restrictions. Avoid using weak passwords or granting unnecessary administrative permissions.
14. Testing the Deployed Servlet
After deployment, verify that the application and servlet mapping work correctly.
Testing Checklist
- Confirm that Tomcat is running.
- Check that the application appears in the deployment location or Manager interface.
- Verify the context path and servlet URL mapping.
- Open the URL in a browser.
- Confirm that the servlet returns the expected response.
- Check the server logs for exceptions or deployment warnings.
- Test any POST forms or database interactions separately.
For the example servlet, test:
http://localhost:8080/MyServletApp-1.0.0/hello
Replace the context path with the actual deployed application name.
15. Understanding the Servlet Lifecycle During Deployment
When a servlet is deployed and accessed, Tomcat manages its lifecycle. The servlet container controls object creation, initialization, request handling, and destruction.
| Lifecycle Stage |
Description |
| Loading and instantiation |
The container loads the servlet class and creates a servlet instance when needed. |
init() |
Called to initialize the servlet before it handles requests. |
service() |
Dispatches incoming HTTP requests to the appropriate handler methods. |
doGet() / doPost() |
Processes GET or POST requests, respectively. |
destroy() |
Called when the container removes the servlet from service. |
A servlet instance may process multiple requests concurrently. Avoid keeping request-specific data in mutable instance variables, and manage resources according to the container's lifecycle.
16. Common Deployment Errors and Solutions
| Error |
Possible Cause |
Solution |
| 404 Not Found |
Incorrect context path or servlet mapping |
Check the WAR name, deployment status, and URL mapping. |
| 500 Internal Server Error |
Unhandled exception or application failure |
Inspect the Tomcat logs and correct the underlying exception. |
| ClassNotFoundException |
Required class is missing from the deployment |
Check package names, compiled classes, and dependencies. |
| NoClassDefFoundError |
Required runtime class or dependency is unavailable |
Verify the packaged libraries and runtime compatibility. |
| Unsupported class version |
Code was compiled for an incompatible Java runtime |
Use a compatible JDK and Tomcat runtime. |
| Servlet API errors |
Mixing javax.servlet and jakarta.servlet or using an incompatible API version |
Align imports, dependencies, and Tomcat version. |
| Port already in use |
Another process is listening on the configured port |
Stop the conflicting process or configure a different connector port. |
| WAR fails to deploy |
Invalid archive, missing files, or deployment configuration errors |
Rebuild the WAR and review the startup and deployment logs. |
| Changes do not appear |
Old application files or cached content remain in use |
Verify the deployed artifact, redeploy carefully, and check browser caching. |
17. Monitoring Logs and Debugging Deployment
Tomcat logs help developers identify startup problems, application errors, missing dependencies, and servlet initialization failures.
- Inspect the files in the Tomcat
logs directory.
- Review startup and deployment messages.
- Look for exception stack traces and the earliest relevant cause.
- Confirm that the expected WAR file and compiled servlet classes are present.
- Use IDE debugging when running the application through a configured local server.
- Avoid displaying internal stack traces or configuration secrets to end users.
18. Deployment Best Practices
- Use compatible versions: Match Java, Tomcat, and Servlet API versions.
- Automate builds: Use Maven or Gradle to produce repeatable deployment artifacts.
- Validate before deployment: Test the WAR in a staging environment first.
- Use clear versioning: Keep track of the artifact version deployed to each environment.
- Protect management interfaces: Restrict Manager access to authorized users.
- Configure secrets safely: Keep passwords, tokens, and sensitive environment-specific values out of source code.
- Use HTTPS in production: Configure TLS appropriately, including when Tomcat operates behind a reverse proxy.
- Monitor application health: Review logs and operational metrics.
- Back up configuration: Preserve deployment settings and required resources.
- Keep dependencies updated: Use supported software versions and apply security updates.
- Use graceful redeployment: Consider active sessions and resource cleanup when replacing applications.
19. Mini Project: Deploy a Welcome Servlet
Objective: Create and deploy a servlet that displays a welcome message on Apache Tomcat.
Project Requirements
- Create a Maven web application named
WelcomeApp.
- Add the compatible Servlet API dependency.
- Create
WelcomeServlet.java extending HttpServlet.
- Map the servlet to
/welcome.
- Build the project to generate a WAR file.
- Deploy the WAR to Tomcat.
- Open the servlet URL in a browser and confirm that the message appears.
- Introduce a deliberate mapping error, observe the result, and correct it.
Expected URL
http://localhost:8080/WelcomeApp/welcome
This example assumes that the deployed WAR is named WelcomeApp.war and no other context configuration changes its context path.
20. Interview Questions and Answers
Q1. What is Apache Tomcat?
Answer: Apache Tomcat is an open-source servlet container used to run Java web applications that comply with supported Servlet specifications.
Q2. What is servlet deployment?
Answer: Servlet deployment is the process of packaging, configuring, and installing a servlet application in a compatible servlet container.
Q3. What is a WAR file?
Answer: A WAR file is a Web Application Archive containing the resources, compiled classes, configuration, and libraries required by a Java web application.
Q4. Where are web applications commonly deployed in Tomcat?
Answer: The default application base is commonly the webapps directory, although the configured application base may differ.
Q5. What is the purpose of web.xml?
Answer: It is a deployment descriptor that can define servlet mappings, filters, listeners, initialization parameters, and other application configuration.
Q6. What is the difference between annotation-based mapping and web.xml mapping?
Answer: Annotation-based mapping uses annotations such as @WebServlet in Java classes, while web.xml defines mappings in an XML configuration file.
Q7. How can a WAR file be deployed on Tomcat?
Answer: A WAR file can commonly be copied into the configured application base directory or deployed through the Tomcat Manager when enabled and properly secured.
Q8. What causes a 404 error after deployment?
Answer: Common causes include an incorrect context path, a wrong servlet URL pattern, or an application that did not deploy successfully.
Q9. Why must the Servlet API version match the Tomcat version?
Answer: Different Tomcat versions support different Servlet specifications and namespaces. Incompatible imports or API requirements can cause compilation or deployment failures.
Q10. How do you troubleshoot a failed deployment?
Answer: Check Tomcat startup logs, confirm the WAR structure, validate dependencies and Java compatibility, and verify servlet mappings and configuration.
21. Practice Exercises
- Install Tomcat and verify that the server starts successfully.
- Create a servlet that displays a welcome message.
- Deploy the servlet using a WAR file.
- Configure the same servlet using
web.xml.
- Test a servlet that handles both GET and POST requests.
- Modify the application context name and determine the new URL.
- Intentionally create an incorrect servlet mapping and troubleshoot the 404 error.
- Inspect Tomcat logs after a failed deployment.
- Create a Maven build that packages the servlet application as a WAR.
- Document the deployment process for a staging environment.
22. Quick Revision Checklist
- Apache Tomcat provides the servlet container runtime.
- A compatible JDK and Tomcat version are required.
- Servlet applications can be deployed as WAR files or unpacked directories.
- The default Tomcat deployment directory is commonly
webapps.
- Servlet mappings connect URL patterns to servlet classes.
@WebServlet and web.xml are common mapping approaches.
- Maven can compile and package an application as a WAR.
- The application context path is commonly based on the deployed WAR or directory name.
- Tomcat logs are essential for debugging deployment problems.
- Servlet API imports must match the target Tomcat version.
- Production deployments should use appropriate access controls and HTTPS.
23. Official Documentation and Learning Resources
24. Conclusion
Deploying servlets on Apache Tomcat is an essential skill in Advanced Java web development. The process involves preparing the Java environment, creating servlet classes, configuring URL mappings, packaging the application, deploying the WAR file, and testing the deployed endpoints.
Understanding Tomcat's directory structure, servlet lifecycle, deployment options, compatibility requirements, and logging tools makes it easier to develop and troubleshoot reliable web applications. Practice deploying small servlet projects before moving to larger applications that include databases, authentication, and business logic.
To continue learning, explore the Advanced Java Training course, register for a course demo, or visit the JustAcademy homepage.