Servlet 3 web.xml Example Configuration

A servlet is a Java class that extends the javax.servlet.Servlet interface. To handle HTTP request you need to extend the javax.servlet.http.HttpServlet abstraction. Servlets interact with Web clients via a request/response paradigm implemented by the servlet container. In the following tutorial we will show you how to create a servlet 3 annotation example configuration.

Project structure

|   +--main
|       +--java
|           +--com
|               +--memorynotfound
|                   |
|       |--resources
|       +--webapp
|           +--WEB-INF
|               |--web.xml

Maven Dependency

Every Servlet Container/Application Server has built in servlet support so you need to set the dependency on provided. So Maven does not include the library in the final built artifact.


Defining our Servlet

The HttpServlet abstract subclass adds additional methods beyond the basic Servlet interface that are automatically called by the service method in the HttpServlet class to aid in processing HTTP-based requests. These methods are

  • doGet for handling HTTP GET requests
  • doPost for handling HTTP POST requests
  • doPut for handling HTTP PUT requests
  • doDelete for handling HTTP DELETE requests
  • doHead for handling HTTP HEAD requests
  • doOptions for handling HTTP OPTIONS requests
  • doTrace for handling HTTP TRACE requests

Typically when developing HTTP-based servlets, a Servlet Developer will only concern himself with the doGet and doPost methods. The other methods are considered to be methods for use by programmers very familiar with HTTP programming.

package com.memorynotfound;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AnnotationServlet extends HttpServlet{

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        out.write("Servlet 3 web.xml example configuration");


Servlet 3 web.xml Configuration

Instead of using Servlet 3 annotation configuration, when using a deployment descriptor you must register your servlet using the <servlet> tag with a required <servlet-name> and <servlet-class> tag which must include the full path of the servlet class which you want to map. To map this servlet to a specific URL you need to add a <servlet-mapping> with the same <servlet-name> and a <url-pattern> to map your servlet to a url pattern.

<web-app xmlns=""
                   " version="3.1">




URL: http://localhost:8080/servlet/example servlet 3 web.xml configuration example



You may also like...