HttpServlet的doGet()和doPost()方法

由于,大多数客户端的请求方式都是GET和POST
因此,HttpServlet中提供了doGet()和doPost()方法
示例程序
在目录D:\cn\itcast\firstapp\servlet中编写RequestMethodServlet类
并且,通过继承HttpServlet类,实现doGet()和doPost()方法的重写
RequestMethodServlet.java
代码如下

package cn.itcast.firstapp.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestMethodServlet extends HttpServlet{
    public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
        PrintWriter out=response.getWriter();
        out.write("this is doGet method");
    }
    public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
        PrintWriter out=response.getWriter();
        out.write("this is doPost method");
    }
}

在chapter04应用的web.xml中,配置RequestMethodServlet的映射路径
代码如下

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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_3_0.xsd"
  version="3.0">
  <servlet>
        <servlet-name>RequestMethodServlet</servlet-name>
        <servlet-class>cn.itcast.firstapp.servlet.RequestMethodServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>RequestMethodServlet</servlet-name>
        <url-pattern>/RequestMethodServlet</url-pattern>
    </servlet-mapping>

</web-app>

编译RequestMethodServlet.java文件
这里写图片描述
将编译生成的RequestMethodServlet.class文件
复制到Tomcat安装目录下的Webapps\chapter04\WEB-INF\classes文件中

GET方式

采用GET方式,访问RequestMethodServlet
启动Tomcat,在浏览器中输入地址
http://localhost:8080/chapter04/RequestMethodServlet
显示如下
这里写图片描述

采用的是GET方式请求Servlet时,会自动调用doGet()方法

POST方式

采用POST方式访问RequestMethodServlet
在目录webapps\chapter04下面,编写一个名为form.html文件
将其中的提交方式设置为POST
Form.html
代码如下

<form action="/chapter04/RequestMethodServlet" method="post">
    姓名:<input type="text" name="name"/><br/>
    密码:<input type="text" name="pwd"/><br/>
    <input type="submit" value="提交">
</form>

启动Tomcat,在浏览器中输入
http://localhost:8080/chapter04/form.html
显示如下
这里写图片描述
单击提交按钮,浏览器界面跳转到了RequestMethodServlet
显示如下
这里写图片描述
采用POST方式请求Servlet时,会自动调用doPost()方法
注意
如果GET和POST请求的处理方式一致,可以在doPost()方法中
直接调用doGet()方法,而不需要将相同的代码写两遍

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值