|
在tomcat下運(yùn)行servlet,需要在web.xml文件中對(duì)servlet進(jìn)行配置,下面用一個(gè)具體的例子一步一步來看一下整個(gè)過程。 1:首先創(chuàng)建一個(gè)web應(yīng)用程序,這里我是用Eclipse建的,就叫web吧,存放路徑C:\eclipse\workspace\web 2:tomcat中,添加conf下的server.xml中的<Context >標(biāo)記 <Context path="/web" reloadable="true" docBase="C:\Eclipse\workspace\web"/> 3:編寫一個(gè)名為ServletTest的servlet程序,具體內(nèi)容如下,應(yīng)該很簡單的,就不多解釋: package test; import javax.servlet.ServletException; public class ServletTest extends HttpServlet{ } 4:將servlet編譯后生成的class文件放到WEB-INF的class目錄下,因?yàn)槲疫@里帶了個(gè)test包,所以生成的文件路徑就是WEB-INF----->class----->test------>ServletTest.class 5:配置web.xml文件,在web應(yīng)用程序的WEB-INF目錄下,新建一個(gè)如下內(nèi)容的web.xml文件 <?xml version="1.0" encoding="Shift_JIS"?> <!DOCTYPE web-app 這里解釋一下這個(gè)文件的內(nèi)容: <servlet-name>標(biāo)簽指定了servlet的名字,主要是下面的<servlet-mapping>用; <servlet-class>說明了servlet存放的class目錄下的位置,這里要加上必要的包名; < servlet-mapping>標(biāo)簽中,<servlet-name>指出要要匹配的servlet的名字,這個(gè)與上邊的< servlet>標(biāo)簽中定義的名字對(duì)應(yīng);<url-pattern>指出了當(dāng)滿足什么條件時(shí),調(diào)用這個(gè)servlet;這里寫的是 /ServletTest 6:啟動(dòng)tomcat,并在瀏覽器中輸入http://localhost:8090/web/ServletTest 則瀏覽器輸出TEST 這里主要想說的就是<url-pattern>,這個(gè)標(biāo)簽指定了servlet的匹配類型,當(dāng)寫成 <url-pattern>/*</url-pattern>時(shí),瀏覽器中輸入http://localhost:8090/web/1111或者http://localhost:8090/web/2222,都會(huì)執(zhí)行這個(gè)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. |
|
|