在tomcat下运行servlet,需要在web.xml文件中对servlet进行配置,下面用一个具体的例子一步一步来看一下整个过程。 1:首先创建一个web应用程序,这里我是用Eclipse建的,就叫web吧,存放路径C:\eclipse\workspace\web 2:tomcat中,添加conf下的server.xml中的<Context >标记 <Context path="/web" reloadable="true" docBase="C:\Eclipse\workspace\web"/> 3:编写一个名为ServletTest的servlet程序,具体内容如下,应该很简单的,就不多解释: package test; import javax.servlet.ServletException; public class ServletTest extends HttpServlet{ } 4:将servlet编译后生成的class文件放到WEB-INF的class目录下,因为我这里带了个test包,所以生成的文件路径就是WEB-INF----->class----->test------>ServletTest.class 5:配置web.xml文件,在web应用程序的WEB-INF目录下,新建一个如下内容的web.xml文件 <?xml version="1.0" encoding="Shift_JIS"?> <!DOCTYPE web-app 这里解释一下这个文件的内容: <servlet-name>标签指定了servlet的名字,主要是下面的<servlet-mapping>用; <servlet-class>说明了servlet存放的class目录下的位置,这里要加上必要的包名; < servlet-mapping>标签中,<servlet-name>指出要要匹配的servlet的名字,这个与上边的< servlet>标签中定义的名字对应;<url-pattern>指出了当满足什么条件时,调用这个servlet;这里写的是 /ServletTest 6:启动tomcat,并在浏览器中输入http://localhost:8090/web/ServletTest 则浏览器输出TEST 这里主要想说的就是<url-pattern>,这个标签指定了servlet的匹配类型,当写成 <url-pattern>/*</url-pattern>时,浏览器中输入http://localhost:8090/web/1111或者http://localhost:8090/web/2222,都会执行这个servlet Addationally, some tips should be noted when developing with eclipse: when you build a web project and edit the web.xml under the WebContent/WEB-INF derectory, the below mapping formet: <servlet-mapping> <servlet-name>DemoServlet</servlet-name> <url-pattern>/DemoServlet</url-pattern> </servlet-mapping> corresponsing to the real url: UrlToYouAppRoot/DemoServlet. So you should refers to this url (or it‘s relative path) in other pages when you call the servlet. |
|
来自: tinaroad > 《WebRalation》