H开发者_JS百科ow i can run a servlet program in tomcat 6.0?
First, you need to declare your servlet in a web deployment descriptor (a web.xml
file) which looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>HelloWorldExample</servlet-name>
<servlet-class>cnx.mywebapp.HelloWorldExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldExample</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Basically, the idea is to declare the fully qualified name of your servlet in the servlet
element and to map it to an url pattern in the servlet-mapping
(the mapping is done via a unique servlet name)
Then, you need to package the whole (the servlet .class
file and the deployment descriptor) in a web application archive (with a .war
extension) which has a defined structure:
mywebapp |-- WEB-INF | |-- classes (java classes, including your servlet, go here) | |-- lib (jar dependencies go here) | `-- web.xml (this is the deployment descriptor) `-- index.jsp
Finally, deploy (copy) the .war in the webapps
directory of Tomcat. To access the servlet:
http://localhost:8080/mywebapp/hello
A B C D
Where:
- A is the hostname where Tomcat is running (the local machine here)
- B is the port Tomcat is listening to (8080 is the default)
- C is the context path to access the webapp (the name of the war by default)
- D is the pattern declared in the web.xml to invoke the servlet
By building a webapp and putting it into the webapp root, just as you would in another version of tomcat or any other servlet container.
精彩评论