First look at the relatively simple-send a simple query string that contains a well-known/value pair to the server, in which case XHP can use Get or post.
GET
function doRequestUsingGET() {
createXMLHttpRequest();
var queryString = " GetAndPostExample? " ;
queryString = queryString + createQueryString()+ " &timeStamp= " + new Date().getTime();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open( " GET " , queryString, true );
xmlHttp.send( null );
}
POST
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);
}
QueryString is the Parameter form of a name/value pair (such as name=lilin&age=23), in the call to the open method, when the request method is post, in order to ensure that the server knows the request parameters in the request body. You need to call setRequestHeader and set the Content-type value to application/x-www-form-urlencoded. It's also not in the request body (don't post it!). )
At this point the server handles:
Import java.io. * ;
Import java.net. * ;
Import Javax.servlet. * ;
Import Javax.servlet.http. * ;
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 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");
}
}