Course topics

By WebNest Studio Engineering Team

Advanced Java Tutorial

Servlet Configuration: web.xml vs Annotations

Before a servlet can handle requests, the container needs to know two things: which URL patterns should route to it, and any initialization parameters it needs. Java web applications support two ways to declare this: the traditional XML deployment descriptor (web.xml), and the modern @WebServlet annotation introduced in Servlet 3.0.

Both approaches configure the same underlying concept — a mapping from a URL pattern to a servlet class — but they differ in where that configuration lives and how flexible it is at deploy time.

The Legacy Approach: web.xml

Before Servlet 3.0, every servlet had to be declared in WEB-INF/web.xml using a <servlet> element (naming the class) paired with a <servlet-mapping> element (binding that name to a URL pattern). This centralizes all routing information in one file, which some teams still prefer for auditability, and it lets operations staff change a URL mapping without recompiling code.

  • <servlet> — declares a logical <servlet-name> and the fully qualified <servlet-class>.
  • <servlet-mapping> — links a <servlet-name> to one or more <url-pattern> values.
  • <init-param> — optional name/value pairs available in the servlet via getInitParameter().

The Modern Approach: @WebServlet

Servlet 3.0 (2009) introduced the @WebServlet annotation, which lets you declare the URL pattern directly on the class, eliminating the need for a matching web.xml entry entirely. This keeps routing information next to the code it affects and is now the default style in almost all new development. Annotations also support init parameters through the nested @WebInitParam annotation.

Choosing Between Them (and Mixing Both)

Annotations are simpler for most projects and reduce boilerplate, but web.xml still has a role: it can override an annotation's URL pattern without touching source code, and some legacy containers or frameworks still expect it. A web.xml entry for a given servlet, if present, takes precedence over that servlet's annotation. Many real projects mix both — annotations for most servlets, and a thin web.xml for cross-cutting settings like session timeout, welcome files, or error pages.

Examples

Same servlet configured with web.xml

Java
<!-- WEB-INF/web.xml -->
<web-app>
    <servlet>
        <servlet-name>greeting</servlet-name>
        <servlet-class>com.webnest.GreetingServlet</servlet-class>
        <init-param>
            <param-name>defaultName</param-name>
            <param-value>Guest</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>greeting</servlet-name>
        <url-pattern>/greet</url-pattern>
    </servlet-mapping>
</web-app>
Output
Requests to /greet are routed to GreetingServlet; getInitParameter("defaultName") returns "Guest".

The same configuration using @WebServlet (no web.xml entry needed)

Java
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

@WebServlet(
    urlPatterns = "/greet",
    initParams = { @WebInitParam(name = "defaultName", value = "Guest") }
)
public class GreetingServlet extends HttpServlet {
    // doGet/doPost implementation unchanged
}
Output
Requests to /greet are routed to GreetingServlet exactly as with the web.xml version — no XML file required.

Common Mistakes

  • Declaring the same URL pattern for two different servlets, which throws a deployment error because mappings must be unique.
  • Forgetting that a web.xml <servlet-mapping> for a class also using @WebServlet can silently override the annotation, causing confusing "which config wins" debugging.
  • Mixing up <servlet-name> across the <servlet> and <servlet-mapping> elements in web.xml, which breaks the routing silently.
  • Assuming annotations work in servlet containers older than Servlet 3.0 (Tomcat 6 and earlier do not support @WebServlet).

Exercise

Using the lesson's Same servlet configured with web.xml example, create a small implementation or design sketch that demonstrates web.xml is the traditional, centralized way to declare servlets, using <servlet> plus <servlet-mapping>.. Add a test case or scenario that would catch Declaring the same URL pattern for two different servlets, which throws a deployment error because mappings must be unique., and describe the expected result.

Show hints
  • Start with The Legacy Approach: web.xml and compare your approach with Same servlet configured with web.xml. Identify the decision or behavior the lesson recommends.
  • Walk through your scenario step by step. Confirm that it follows web.xml is the traditional, centralized way to declare servlets, using <servlet> plus <servlet-mapping>. and that it would catch the failure described by Declaring the same URL pattern for two different servlets, which throws a deployment error because mappings must be unique..

Quick quiz

1. Which choice is a mistake to avoid in Servlet Configuration: web.xml vs Annotations?

  • A. Forgetting that a web.xml <servlet-mapping> for a class also using @WebServlet can silently override the annotation, causing confusing "which config wins" debugging.
  • B. web.xml is the traditional, centralized way to declare servlets, using <servlet> plus <servlet-mapping>.
  • C. Declaring the same URL pattern for two different servlets, which throws a deployment error because mappings must be unique.
Show answer

C. Avoid this approach: Declaring the same URL pattern for two different servlets, which throws a deployment error because mappings must be unique. The lesson recommends: web.xml is the traditional, centralized way to declare servlets, using <servlet> plus <servlet-mapping>.

Interview questions

A teammate is about to make this mistake: Declaring the same URL pattern for two different servlets, which throws a deployment error because mappings must be unique. How would you diagnose and correct it using the lesson's guidance?

Show answer

web.xml is the traditional, centralized way to declare servlets, using <servlet> plus <servlet-mapping>. Apply this in The Legacy Approach: web.xml; the example Same servlet configured with web.xml shows one way to do it. Avoid Declaring the same URL pattern for two different servlets, which throws a deployment error because mappings must be unique. and explain how your implementation or design prevents that failure.

Key Points to Remember

  • web.xml is the traditional, centralized way to declare servlets, using <servlet> plus <servlet-mapping>.
  • @WebServlet(urlPatterns = "...") is the modern Servlet 3.0+ approach, keeping routing next to the class.
  • A matching web.xml entry overrides an @WebServlet annotation for the same servlet.
  • Both approaches support init parameters, retrieved in code via getInitParameter().

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

These examples need a JDK project with their libraries on your computer, so they can be copied but not run here. Codelab runs Python, FastAPI backends with SQLite, plain Java 17 and HTML/CSS/JavaScript.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering