java doget dopost_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的映射路径

代码如下

RequestMethodServlet

cn.itcast.firstapp.servlet.RequestMethodServlet

RequestMethodServlet

/RequestMethodServlet

编译RequestMethodServlet.java文件

f7f7d11b131215b95371b5be288a3cf2.png

将编译生成的RequestMethodServlet.class文件

复制到Tomcat安装目录下的Webapps\chapter04\WEB-INF\classes文件中

GET方式

采用GET方式,访问RequestMethodServlet

启动Tomcat,在浏览器中输入地址

http://localhost:8080/chapter04/RequestMethodServlet

显示如下

9cdd5ede90cf750f36883465b2eaf986.png

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

POST方式

采用POST方式访问RequestMethodServlet

在目录webapps\chapter04下面,编写一个名为form.html文件

将其中的提交方式设置为POST

Form.html

代码如下

姓名:

密码:

启动Tomcat,在浏览器中输入

http://localhost:8080/chapter04/form.html

显示如下

0d87c8a66bf36ff1f7d7676112179d04.png

单击提交按钮,浏览器界面跳转到了RequestMethodServlet

显示如下

cd8e8e6aef6846ac752fb57a4bd42fb1.png采用POST方式请求Servlet时,会自动调用doPost()方法 注意 如果GET和POST请求的处理方式一致,可以在doPost()方法中 直接调用doGet()方法,而不需要将相同的代码写两遍


版权声明:本文为weixin_29324401原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。