Adding a Simple Servlet

A web application with a single JSP page and no configured servlets is next to useless. Let’s add a simple servlet to this application and make some changes to the pom.xml and web.xml to support this change. First, we’ll need to create a new package under src/main/java named org.sonatype.mavenbook.web:

$ mkdir -p src/main/java/org/sonatype/mavenbook/web
$ cd src/main/java/org/sonatype/mavenbook/web

Once you’ve created this package, change to the src/main/java/org/sonatype/mavenbook/web directory and create a class named SimpleServlet in SimpleServlet.java, which contains the code shown in Example 5-5.

Example 5-5. SimpleServlet class

package org.sonatype.mavenbook.web;

import java.io.*;
import javax.servlet.*;                                                         
import javax.servlet.http.*;

public class SimpleServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException {
    
        PrintWriter out = response.getWriter();
        out.println( "SimpleServlet Executed" );
        out.flush();
        out.close();
    }
}

Our SimpleServlet class is just that: a servlet that prints a simple message to the response’s Writer. To add this servlet to your web application and map it to a request path, add the servlet and servlet-mapping elements shown in Example 5-6 to your project’s web.xml file. The web.xml file can be found in src/main/webapp/WEB-INF.

Example 5-6. Mapping the simple servlet

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application ...

Get Maven: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.