傳送參數給服務器的例子

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的惟一性,從而避免瀏覽器緩存結果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章