1。getAndPostExample.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sending Request Data Using GET and POST</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function createQueryString() {
var firstName = document.getElementById("firstName").value;
var middleName = document.getElementById("middleName").value;
var birthday = document.getElementById("birthday").value;
var queryString = "firstName=" + firstName + "&middleName=" + middleName
+ "&birthday=" + birthday;
return queryString;
}
function doRequestUsingGET() {
createXMLHttpRequest();
var queryString = "GetAndPostExample?";
queryString = queryString + createQueryString()
+ "&timeStamp=" + new Date().getTime();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", queryString, true);
xmlHttp.send(null);
}
function doRequestUsingPOST() {
createXMLHttpRequest();
var url = "GetAndPostExample?timeStamp=" + new Date().getTime();
var queryString = createQueryString();
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded;");
xmlHttp.send(queryString);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
parseResults();
}
}
}
function parseResults() {
var responseDiv = document.getElementById("serverResponse");
if(responseDiv.hasChildNodes()) {
responseDiv.removeChild(responseDiv.childNodes[0]);
}
var responseText = document.createTextNode(xmlHttp.responseText);
responseDiv.appendChild(responseText);
}
</script>
</head>
<body>
<h1>Enter your first name, middle name, and birthday:</h1>
<table>
<tbody>
<tr>
<td>First name:</td>
<td><input type="text" id="firstName"/>
</tr>
<tr>
<td>Middle name:</td>
<td><input type="text" id="middleName"/>
</tr>
<tr>
<td>Birthday:</td>
<td><input type="text" id="birthday"/>
</tr>
</tbody>
</table>
<form action="#">
<input type="button" value="Send parameters using GET" οnclick="doRequestUsingGET();"/>
<br/><br/>
<input type="button" value="Send parameters using POST" οnclick="doRequestUsingPOST();"/>
</form>
<br/>
<h2>Server Response:</h2>
<div id="serverResponse"></div>
</body>
</html>
2.GetAndPostExample.java
package ajaxbook.chap3;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetAndPostExample extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request,
HttpServletResponse response, String method)
throws ServletException, IOException {
//Set content type of the response to text/xml
response.setContentType("text/xml");
//Get the user's input
String firstName = request.getParameter("firstName");
String middleName = request.getParameter("middleName");
String birthday = request.getParameter("birthday");
//Create the response text
String responseText = "Hello " + firstName + " " + middleName
+ ". Your birthday is " + birthday + "."
+ " [Method: " + method + "]";
//Write the response back to the browser
PrintWriter out = response.getWriter();
out.println(responseText);
//Close the writer
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Process the request in method processRequest
processRequest(request, response, "GET");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Process the request in method processRequest
processRequest(request, response, "POST");
}
}
3.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>TestAjax</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>GetAndPostExample</servlet-name>
<servlet-class>ajaxbook.chap3.GetAndPostExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetAndPostExample</servlet-name>
<url-pattern>/GetAndPostExample</url-pattern>
</servlet-mapping>
</web-app>
这两种方法的主要区别在于,POST方法将参数串放在请求体中发送,而GET方法是将参数追加到URL中发送
从发送到服务器的数据量来讲,POST方法更为灵活。使用GET请求所能发送的数据量通常是固定的,
因浏览器不同而有所差异,而POST方法可以发送任意量的数据。
HTML form元素允许通过将form元素的method属性设置为GET或POST来指定所需的方法。
在提交表单时,form元素自动根据其method属性的规则对input元素的数据进行编码。
XMLHttpRequest对象没有这种内置行为。相反,要由开发人员使用JavaScript创建查询串,
其中包含的数据要作为请求的一部分发送给服务器。
不论使用的是GET请求还是POST请求,创建查询串的技术是一样的。惟一的区别是,
当使用GET发送请求时,查询串会追加到请求URL中,
而使用POST方法时,则在调用XMLHttpRequest对象的send()方法时发送查询串。
为了确保服务器知道请求体中有请求参数,需要调用setRequestHeader,将Content-Type值设置为application/x- www-form-urlencoded。最后,调用send()方法,并把查询串作为参数传递给这个方法。
为什么要把时间戳追加到目标URL?
在某些情况下,有些浏览器会把多个XMLHttpRequest请求的结果缓存在同一个URL。如果对每个请求的响应不同,这就会带来不好的结果。把当前时间戳追加到URL的最后,就能确保URL的惟一性,从而避免浏览器缓存结果。