运行访问一个Servlet的方法(Web Application):
在webapps目录下根据规范建立文件夹my,其中有文件夹WEB-INF和html文件。。

    <WEB-INF中有一个文件web.xml、文件夹lib、文件夹classes。

        <<web.xml的内容:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://Java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://Java.sun.com/xml/ns/j2ee http://Java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">

<Servlet>
    <Servlet-name>mosquito</Servlet-name>    //这个名字与下面的一致
        <Servlet-class>HelloWorldServlet</Servlet-class>    //这里是编译好的类的名字(包括坐在包的完整名字)
</Servlet>

<Servlet-mapping>
    <Servlet-name>mosquito</Servlet-name>    //这个名字与上面的一致
        <url-pattern>/abcmosquito</url-pattern>    //根据这个名字访问Servlet,必须要有"/"
</Servlet-mapping>
</web-app>

        <<classes:存放编译好的Servlet文件

    <index.html中的内容:

        <<1.用get方式提交表单:
<form action=http://127.0.0.1:8888/my/abcmosquito method=get>
    <input type=text name=test>
    <input type=submit value="提交">
</from>

        <<2.用post方式提交表单:
<form action=http://127.0.0.1:8888/my/abcmosquito method=post>
    <input type=text name=test>
    <input type=submit value="提交">
</from>

在IE浏览器中输入http://127.0.0.1:8888/my/index.html,点击提交,可以根据以上两个不同的html文件用不同方式提交表单。(共有8种提交方式,常用的只有以上两种)

Servlet的基本形式(eclipse中工程必须引入jar包,右键点击Properties,点击Java Build Pash,Libraries,Add External JARs,选择Tomcat中lib的Servlet-api.jar):
import Java.io.IOException;
import Java.io.PrintWriter;
import Javax.Servlet.ServletException;
import Javax.Servlet.http.HttpServlet;
import Javax.Servlet.http.HttpServletRequest;
import Javax.Servlet.http.HttpServletResponse;


public class HelloWorldServlet extends HttpServlet{    //Servlet都必须实现Servlet接口,Servlet可以运行在各种服务器中,因为这里是运行在Http服务器故继承HttpServlet,HttpServlet实现了Servlet接口

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        System.out.println("dopost......");
        doGet(req,resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        System.out.println("doget......");
        resp.setContentType("text/html";charset="gbk");    //加入头信息,是浏览器能正确输出中文
        PrintWriter out = resp.getWriter();
        out.println("<html><head><title></title></head><body>你好hello world!!!</body></html>");
        out.flush();
        out.close();
    }

    private static final long serialVersionUID = 1L;
    
}


在IE中输入以下路径即可访问Servlet:http://127.0.0.1:8888/my/abcmosquito

 

posted on 2014-04-21 18:55  mosquito_real  阅读(479)  评论(0编辑  收藏  举报