11.5. Installing a Servlet in Tomcat
Problem
You’ve created a servlet .class
file, and
you want to run it in
Tomcat.
Solution
Place the .class
file into the correct Tomcat
directory (such as
webapps\Ch11\WEB-INF\class\org\cookbook\ch11
).
Add servlet data to the web.xml
file, restart
Tomcat, and navigate to your servlet’s URL, such as
http://localhost:8080/ch11/org.cookbook.ch11.ServletClass.
Discussion
To install a .class
file, you can simply copy it
over to the correct directory in the Tomcat directory structure.
Because the servlet is in the org.cookbook.ch11
package, and the directory structure must mirror the package
structure, put ServletClass.class
in
webapps\Ch11\WEB-INF\class\org\cookbook\ch11
:
webapps
|_ _ch11
|_ _WEB-INF
|_ _classes
| |_ _org
| |_ _cookbook
| |_ _ch11 Put the servlet's code here
|_ _lib
To set up this servlet with Tomcat, we’ll create the
deployment descriptor file, web.xml
. In this XML
file, we’ll use two elements,
<servlet>
and
<servlet-mapping>
, to register this servlet
with Tomcat. The web.xml
file
we’ll use appears in Example 11-3.
Example 11-3. web.xml
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>Example Applications</display-name> <servlet> <servlet-name>Servlet</servlet-name> <servlet-class>org.cookbook.ch11.ServletClass</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet</servlet-name> <url-pattern>/org.cookbook.ch11.ServletClass</url-pattern> ...
Get Eclipse Cookbook 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.