分享

servlet 与web.xml的设置问题

 tinaroad 2007-08-09

在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 java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletTest extends HttpServlet{
 protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
  doPost(arg0,arg1);
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");
  ServletOutputStream out=response.getOutputStream();
  out.println("<html>");
  out.println("<body>");
  out.println("TEST");
  out.println("</body>");
  out.println("</html>"); 
 }

}

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
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  "http://java./dtd/web-app_2_3.dtd">
<web-app>
 <servlet>
  <servlet-name>ServletTest</servlet-name>
  <servlet-class>test.ServletTest</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>ServletTest</servlet-name>
  <url-pattern>/ServletTest</url-pattern>  
 </servlet-mapping>
</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
也就是在这个地方可以用一些通配符表示。

END!

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.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多