生活随笔
收集整理的這篇文章主要介紹了
HttpServlet的doGet()和doPost()方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
由于,大多數(shù)客戶端的請求方式都是GET和POST
因此,HttpServlet中提供了doGet()和doPost()方法
示例程序
在目錄D:\cn\itcast\firstapp\servlet中編寫RequestMethodServlet類
并且,通過繼承HttpServlet類,實(shí)現(xiàn)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應(yīng)用的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/javaeehttp://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文件
復(fù)制到Tomcat安裝目錄下的Webapps\chapter04\WEB-INF\classes文件中
GET方式
采用GET方式,訪問RequestMethodServlet
啟動Tomcat,在瀏覽器中輸入地址
http://localhost:8080/chapter04/RequestMethodServlet
顯示如下
采用的是GET方式請求Servlet時,會自動調(diào)用doGet()方法
POST方式
采用POST方式訪問RequestMethodServlet
在目錄webapps\chapter04下面,編寫一個名為form.html文件
將其中的提交方式設(shè)置為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
顯示如下
單擊提交按鈕,瀏覽器界面跳轉(zhuǎn)到了RequestMethodServlet
顯示如下
采用POST方式請求Servlet時,會自動調(diào)用doPost()方法
注意
如果GET和POST請求的處理方式一致,可以在doPost()方法中
直接調(diào)用doGet()方法,而不需要將相同的代碼寫兩遍
總結(jié)
以上是生活随笔為你收集整理的HttpServlet的doGet()和doPost()方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。