How do I configure servlets in web.xml?

In a Jakarta EE (formerly Java EE) application, you can configure servlets in the web.xml deployment descriptor. The web.xml file is located in the WEB-INF directory of your project. Here’s how you can configure a servlet in web.xml step-by-step:

1. Declare the Servlet

You define the servlet by giving it a name and specifying its implementing class.

<servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>org.kodejava.servlet.MyServlet</servlet-class>
</servlet>

2. Map the Servlet to a URL Pattern

After declaring the servlet, you specify the URL patterns (endpoints) it should handle.

<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/myServlet</url-pattern>
</servlet-mapping>

The servlet-name in the <servlet-mapping> must match the one defined in the <servlet> section.

Complete Example

Below is a complete example of web.xml configuration for a servlet:

<?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">

    <!-- Declare the servlet -->
    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>org.kodejava.servlet.MyServlet</servlet-class>
    </servlet>

    <!-- Map the servlet to a URL pattern -->
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/myServlet</url-pattern>
    </servlet-mapping>

</web-app>

Understanding the Tags

  • <servlet>: Declares the servlet, including its name and fully qualified class name.
  • <servlet-name>: A unique name for your servlet (used in <servlet-mapping> to link configuration).
  • <servlet-class>: The fully qualified class name of the servlet (e.g., org.kodejava.servlet.MyServlet).
  • <servlet-mapping>: Maps the declared servlet to specific URL patterns (e.g., /myServlet).
  • <url-pattern>: Specifies the URL or set of URLs that the servlet will handle.

Notes:

  1. URL Patterns:
    • /myServlet matches a specific path.
    • /* matches all paths.
    • /example/* matches all paths under /example.
  2. Multiple Servlet Mappings: You can map the same servlet to multiple URL patterns by adding multiple <servlet-mapping> entries.

  3. Override Annotations: If you use @WebServlet annotations in your servlet class, you generally won’t need to configure the servlet in web.xml. However, web.xml still allows more control over deployment and compatibility with older specifications.
  4. Jakarta EE Web.xml Version:
    The <web-app> version should match the Jakarta EE version you are using. For Jakarta EE 10, use version="6.0" as shown above.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.