创建自己的HttpServlet类,4个步骤:
(1)扩展HttpServlet抽象类。
(2)覆盖HttpServlet的部分方法,如覆盖doGet()或doPost方法。
(3)获取HTTP请求信息,例如通过HttpServletRequest对象来检索HTML表单所提交的数据或URL上的查询字符串。无论是HTML表单数据还是URL上的查询字符串,在
HttpServletRequest对象中都以参数名/参数值的形式存放,可以通过一下方法检索参数信息:
getParameterNames():返回一个Enumeration对象,它包含了所有的参数名信息
getParameter(String name):返回参数名name对应的参数值
getParameterValues():返回一个Enumeration对象,它包含了所有的参数值信息HttpServletResponse对象有一个getWriter()方法。该方法返回一个PrintWriter对象。使用
PrintWriter的print()或println()方法可以向客户端发送字符串数据流。
(4)生成HTTP响应结果。通过HttpServletResponse对象可以生成响应结果。HttpServletResponse对象有一个getWriter()方法,该方法返回一个PrintWriter对象。使用
PrintWriter的print()或println()方法可以向客户端发送字符串数据流。
例:
package mypack;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet//第一步
{
//覆盖doGet()方法
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
//第三步:获取HTTP请求中的参数信息
String clientName=request.getParameter("clientName");
if(clientNme!=null)
clientName=new String(clientName.getBytes("ISO-8859-1"),"GB2312");
else
clientName="我的朋友";
//第四步:生成HTTP响应结果
PrintWriter out;
String title="HelloServlet";
String heading1="This is output from HelloServlet by doGet:";
response.setContentType("text/html;charset=GB2312");/*MIME类型*/
out=response.getWriter();
out.print("
"+title+"");out.print("
");out.print(heading1);
out.print("
"+clientName+":您好");
out.print("");
out.close();
}
}
部署Servlet:
在WEB-INF下的Web.xml里增加如下代码:
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">
Hello
mypack.Hello
Hello
/Hello
posted on 2009-03-08 12:16 乱せ英豪 阅读(1569) 评论(0) 编辑 收藏