要想充分发挥ajax的强大功能,这要求你向服务器发送一些上下文数据。
XMLHttpRequest对象的工作与以往惯用的HTTP技术(GET和POST)是一样的。
在下面的例子中,主要介绍这两种请求方式。
其中GET请求,我们向应用程序发送了3个参数:firstName,middleName,birthday.
其中资源URL和参数之间要用一个问号(?),问号后面就是名/值对。其采用name=value的形式,各个名值对之间用与(&)号分隔。
如:
服务器知道如何获取URL中的命名参数。
采用POST方法向服务器发送命名参数时,与采用GET时类似。POST方法也会将参数编码为名/值对。
这两种方式的主要区别在于,POST方法将参数串放在请求体中发送,而GET方法是将参数追加到URL中发送。
该示例有两个文件,其一为getandpost.html,另一个为servlet GetAndPostExample.java
详细代码如下:
- package ajax.study;
-
-
import java.io.IOException;
-
import java.io.PrintWriter;
-
-
import javax.servlet.ServletException;
-
import javax.servlet.http.HttpServlet;
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
-
public class GetAndPostExample extends HttpServlet {
-
-
-
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 brower
-
PrintWriter out = response.getWriter();
-
out.println(responseText);
-
-
//close the writer
-
out.close();
-
-
-
}
-
-
-
-
-
public void doGet(HttpServletRequest request, HttpServletResponse response)
-
throws ServletException, IOException {
-
//process the request in method processRequest
-
processRequest(request,response,"GET");
-
-
}
-
-
public void doPost(HttpServletRequest request, HttpServletResponse response)
-
throws ServletException, IOException {
-
//process the request in method processRequest
-
processRequest(request,response,"POST");
-
}
-
-
-
-
}
阅读(1950) | 评论(0) | 转发(1) |