Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Servlet Deployment WAR File, Tomcat, Production Deployment: Tutorial, Examples, FAQs & Interview Tips

What is Servlet Deployment?

Servlet deployment is the process of packaging, configuring, and installing a Java web application on a servlet tl-container (like Apache Tomcat, Jetty, or WildFly) so it can handle HTTP requests. Deployment involves creating a WAR file, configuring the deployment descriptor, and deploying it to the server.

Understanding deployment is crucial for moving applications from development to production environments. Proper deployment ensures your servlets are accessible, secure, and performant in real-world scenarios.

WAR File Structure

A WAR (Web Application Archive) file is a ZIP file with a .war extension that packages a Java web application for deployment. It follows a standard directory structure defined by the Java Servlet specification:

  • Root Directory - Contains public resources like HTML, JSP, CSS, JavaScript, and images that are directly accessible to clients
  • WEB-INF/ - Protected directory that clients cannot access directly; contains application configuration and compiled code
  • WEB-INF/web.xml - Deployment descriptor that configures servlets, filters, listeners, and other components
  • WEB-INF/classes/ - Contains compiled Java class files organized in package structure
  • WEB-INF/lib/ - Contains JAR files for third-party libraries and dependencies
myapp.war
├── index.jsp                    <- Public web resources
├── about.html
├── css/
│   └── style.css
├── js/
│   └── app.js
├── images/
└── WEB-INF/                     <- Protected directory (not accessible by clients)
    ├── web.xml                  <- Deployment descriptor
    ├── classes/                 <- Compiled .class files
    │   └── com/example/
    │       ├── HelloServlet.class
    │       └── UserDAO.class
    ├── lib/                     <- JAR dependencies
    │   ├── mysql-connector.jar
    │   └── jstl.jar
    └── views/                   <- Protected JSP views
        ├── login.jsp
        └── dashboard.jsp
Complete web.xml Configuration
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <display-name>My Servlet Application</display-name>
    <description>A sample servlet web application</description>

    <!-- Context-wide init parameters -->
    <context-param>
        <param-name>appName</param-name>
        <param-value>MyApp</param-value>
    </context-param>

    <!-- Servlet declarations -->
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.example.HelloServlet</servlet-class>
        <init-param>
            <param-name>greeting</param-name>
            <param-value>Hello</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

    <!-- Filter -->
    <filter>
        <filter-name>LoggingFilter</filter-name>
        <filter-class>com.example.filters.LoggingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>LoggingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Session configuration -->
    <session-config>
        <session-timeout>30</session-timeout>
        <cookie-config>
            <http-only>true</http-only>
            <secure>true</secure>
        </cookie-config>
    </session-config>

    <!-- Welcome files -->
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <!-- Error pages -->
    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/views/error-404.jsp</location>
    </error-page>
    <error-page>
        <exception-type>java.lang.Exception</exception-type>
        <location>/WEB-INF/views/error-500.jsp</location>
    </error-page>

</web-app>

Maven WAR Plugin and Deployment

Maven simplifies WAR file creation and deployment through the Maven WAR Plugin. This plugin automatically packages your application following the standard WAR structure and can be configured for different deployment scenarios.

The maven-war-plugin handles resource filtering, dependency management, and WAR file generation. Setting failOnMissingWebXml to false allows deployment without web.xml when using annotations.

Maven WAR Plugin Configuration
<build>
    <finalName>myapp</finalName>
    <plugins>
        <!-- Maven WAR Plugin -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.3.2</version>
            <configuration>
                <warName>myapp</warName>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>

        <!-- Tomcat Maven Plugin (for development) -->
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <port>8080</port>
                <path>/myapp</path>
            </configuration>
        </plugin>
    </plugins>
</build>

<!-- Build: mvn clean package -->
<!-- Run with Tomcat plugin: mvn tomcat7:run -->
<!-- Deploy: copy target/myapp.war to TOMCAT_HOME/webapps/ -->

Deployment Methods

There are several ways to deploy a servlet application to a server:

1. Manual Deployment

Copy the WAR file to the server's deployment directory. For Tomcat, this is TOMCAT_HOME/webapps/. The server automatically extracts and deploys the application.

Manual Deployment Commands
# Build WAR file with Maven
mvn clean package

# Copy to Tomcat webapps directory
cp target/myapp.war /opt/tomcat/webapps/

# Tomcat automatically deploys the application
# Access at: http://localhost:8080/myapp/

# To undeploy, simply delete the WAR and extracted folder
rm -rf /opt/tomcat/webapps/myapp*

2. Tomcat Manager Deployment

Use Tomcat's web-based Manager application to deploy, undeploy, start, stop, and reload applications through a GUI or REST API.

Tomcat Manager Configuration
<!-- Add to TOMCAT_HOME/conf/tomcat-users.xml -->
<tomcat-users>
    <role rolename="manager-gui"/>
    <role rolename="manager-script"/>
    <user username="admin" password="admin123" roles="manager-gui,manager-script"/>
</tomcat-users>

<!-- Access Manager at: http://localhost:8080/manager/html -->
# Deploy via Tomcat Manager REST API
curl -u admin:admin123 \
  --upload-file target/myapp.war \
  "http://localhost:8080/manager/text/deploy?path=/myapp&update=true"

# List deployed applications
curl -u admin:admin123 \
  "http://localhost:8080/manager/text/list"

# Undeploy application
curl -u admin:admin123 \
  "http://localhost:8080/manager/text/undeploy?path=/myapp"

3. Maven Tomcat Plugin

Deploy directly from Maven using the Tomcat Maven Plugin. This is ideal for development and testing environments.

Maven Tomcat Plugin Commands
# Run embedded Tomcat server (development)
mvn tomcat7:run

# Deploy to remote Tomcat server
mvn tomcat7:deploy

# Redeploy (update existing deployment)
mvn tomcat7:redeploy

# Undeploy from server
mvn tomcat7:undeploy

# Run on specific port
mvn tomcat7:run -Dmaven.tomcat.port=9090

Deployment Descriptor (web.xml)

The web.xml file is the deployment descriptor that configures your web application. While Servlet 3.0+ supports annotations, web.xml is still widely used for centralized configuration.

Key web.xml Elements

  • <servlet> - Declares a servlet and its initialization parameters
  • <servlet-mapping> - Maps URL patterns to servlets
  • <filter> - Declares filters for request/response processing
  • <listener> - Registers event listeners for application lifecycle
  • <context-param> - Defines application-wide initialization parameters
  • <session-config> - Configures session timeout and cookie settings
  • <error-page> - Maps error codes and exceptions to error pages
  • <welcome-file-list> - Specifies default files for directory requests
  • <security-constraint> - Defines access control rules

Annotation-Based Configuration

Servlet 3.0 introduced annotations as an alternative to web.xml configuration. Annotations are placed directly in servlet classes, making configuration more maintainable.

Servlet with Annotations
package com.example;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(
    name = "HelloServlet",
    urlPatterns = {"/hello", "/greet"},
    loadOnStartup = 1,
    initParams = {
        @WebInitParam(name = "greeting", value = "Hello"),
        @WebInitParam(name = "language", value = "en")
    }
)
public class HelloServlet extends HttpServlet {
    
    private String greeting;
    
    @Override
    public void init() throws ServletException {
        greeting = getInitParameter("greeting");
        System.out.println("HelloServlet initialized with greeting: " + greeting);
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        String name = request.getParameter("name");
        if (name == null || name.isEmpty()) {
            name = "World";
        }
        
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>" + greeting + ", " + name + "!</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

// No web.xml needed! Access at: http://localhost:8080/myapp/hello?name=John

Context Path and URL Mapping

The context path is the URL prefix for your application. If you deploy myapp.war, the context path is /myapp. All servlet URLs are relative to this context path.

URL Pattern Examples

URL Pattern Matches Example
/hello Exact match /myapp/hello
/user/* Path prefix /myapp/user/profile, /myapp/user/settings
*.do Extension match /myapp/login.do, /myapp/register.do
/ Default servlet All unmatched requests
/* All requests Every request (use for filters)

Deployment Best Practices

  • Use meaningful context paths - Choose descriptive names like /shop instead of /app1
  • Externalize configuration - Store database credentials and API keys outside the WAR file
  • Enable security - Use HTTPS, secure cookies, and implement authentication/authorization
  • Optimize resources - Minify CSS/JS, compress images, enable GZIP compression
  • Configure logging - Use proper logging frameworks (Log4j, SLF4J) instead of System.out
  • Set session timeout - Configure appropriate session timeout based on application needs
  • Handle errors gracefully - Define custom error pages for 404, 500, and other errors
  • Version your deployments - Include version numbers in WAR filenames (myapp-1.0.0.war)
  • Test before production - Deploy to staging environment first
  • Monitor performance - Use JMX, application monitoring tools, and server logs

Common Deployment Issues

1. ClassNotFoundException

Cause: Missing JAR files in WEB-INF/lib or incorrect package structure in WEB-INF/classes

Solution: Verify all dependencies are included in the WAR file and class files are in correct package directories

2. 404 Not Found

Cause: Incorrect URL pattern, servlet not registered, or wrong context path

Solution: Check servlet mapping in web.xml or @WebServlet annotation, verify context path

3. Port Already in Use

Cause: Another application is using port 8080

Solution: Change Tomcat port in server.xml or stop the conflicting application

4. OutOfMemoryError

Cause: Insufficient heap memory for the application

Solution: Increase JVM heap size: export CATALINA_OPTS="-Xms512m -Xmx2048m"

Production Deployment Checklist

  • ✓ Remove debug code and System.out.println statements
  • ✓ Configure production database connection
  • ✓ Enable HTTPS and secure cookies
  • ✓ Set appropriate session timeout
  • ✓ Configure custom error pages
  • ✓ Enable GZIP compression
  • ✓ Set up logging to files (not console)
  • ✓ Configure firewall rules
  • ✓ Set up backup and recovery procedures
  • ✓ Test all critical functionality
  • ✓ Monitor server resources (CPU, memory, disk)
  • ✓ Document deployment procedures

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.