Writing and Testing a Servlet

We use the Simple.java test servlet described earlier to demonstrate how to install a servlet. First of all we create a directory, .../site.tomcat, and in it a subdirectory called servlets — this is where we will end up pointing Tomcat. In .../site.tomcat/servlets, we create a directory WEB-INF (this is where Tomcat expects to find stuff). In WEB-INF we create another subdirectory called classes. Then we copy Simple.class to .../site.tomcat/servlets/WEB-INF/classes. We then associate the Simple class with a servlet unimaginatively called “test”, by creating .../site.tomcat/servlets/WEB-INF/web.xml, containing:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
    <servlet>
        <servlet-name>
            test
        </servlet-name>
        <servlet-class>
            Simple
        </servlet-class>
    </servlet>
</web-app>

Finally, we make Tomcat aware of all this by associating the .../site.tomcat/servlets directory with a context by creating conf/apps-simple.xml (remember, this file will automatically be read by the default configuration) containing:

<?xml version="1.0" encoding="ISO-8859-1"?>
<webapps>
   <Context path="/simple" 
            docBase=".../site.tomcat/servlets" 
            debug="0" 
            reloadable="true" > 
              <LogSetter name="simple_tc.log" path="logs/simple.log" />
              <LogSetter name="simple_servlet_log" 
                         path="logs/simple_servlet.log" 
                         servletLogger="true"/>
  </Context>
</webapps>

Obviously,

Get Apache: The Definitive Guide, 3rd Edition 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.