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, docBase must be set to the actual path of our directory. The path parameter specifies the first part of the URL that will access this context. The context can contain plain HTML, as well as servlets and JSPs. Servlets appear in the servlet subdirectory of the path, so to access the Simple servlet with the previous configuration, we would use the URL http://.../simple/servlet/test. Surfing to http://.../simple/servlet/test?a=b&c=d&c=e produces the following output:

Simple Servlet

c[0]=d
c[1]=e
a[0]=b