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
|_ _libTo 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> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access