由于,大多数客户端的请求方式都是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()方法,而不需要将相同的代码写两遍