How the parameters in the AJAX POST request are obtained in the servlet as form data and request payload

Source: Internet
Author: User
Tags http post webp chrome developer

In the HTTP request, if it is a GET request, then the form parameter is appended to the URL in the form of name=value&name1=value1, and if it is a POST request, then the form parameter is in the request body, also in the name=value&name1= The form of value1 in the request body. The Chrome developer tool can be seen as follows (here is a readable form, not a request format for the real HTTP request protocol):

GET Request:

 requesturl:http:// 127.0.0.1:8080/test/ Test.do?name=mikan&address=street  request method:get Status Code:  200 OK Request Headers Accept:text /html,application/xhtml+xml,application/xml; Q=0.9,image/webp,*/*  ;q=0.8 accept-encoding: GZIP,DEFLATE,SDCH accept-language:zh-cn,zh;q=0.8,en;q=0.6 alexatoolbar-alx_ns_ph:alexatoolbar/alxg-3.2 Connection : keep-alive cookie:jsessionid=74ac93f9f572980b6fc10474cd8edd8d host:127.0.0.1:8080 Referer:http://127.0.0.1:8080/ test/index.jsp user-agent:mozilla/5.0 (Windows NT 6.1) applewebkit/537.36 (khtml, like Gecko) chrome/33.0.1750.149  safari/537.36 Query String Parameters name:mikan address:street Response Headers content-length:2 Date:sun, 11 10:42:38 GMT server:apache-coyote/1.1  

POST request:

Requesturl:http://127.0.0.1:8080/test/test.doRequest method:post Status Code:200OK Request Headers accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*; q=0.8 accept-encoding:gzip,deflate,sdch accept-language:zh-cn,zh;q=0.8,en;q=0.6 AlexaToolbar-ALX_NS_PH: alexatoolbar/alxg-3.2 cache-control:max-age=0 connection:keep-alive content-length:25 Content-Type:application/ x-www-form-urlencoded cookie:jsessionid=74ac93f9f572980b6fc10474cd8edd8d host:127.0.0.1:8080 Origin:http:// 127.0.0.1:8080 referer:http://127.0.0.1:8080/test/index.jsp user-agent:mozilla/5.0 (Windows NT 6.1) AppleWebKit/ 537.36 (khtml, like Gecko) chrome/33.0.1750.149 safari/537.36 Form Data name:mikan address:street Response Heade RS content-length:2 Date:sun, 11:05:33 GMT server:apache-coyote/1.1

Note here that the content-type of the POST request is application/x-www-form-urlencoded, and the parameter is in the request body, which is the form Data in the request above.

In a servlet, form parameters can be obtained in the form of Request.getparameter (name).

And if you use the native Ajax POST request:

functiongetxmlhttprequest () {varXHR; if(window. ActiveXObject) {XHR=NewActiveXObject ("Microsoft.XMLHTTP"); }Else if(window. XMLHttpRequest) {XHR=NewXMLHttpRequest (); }Else{XHR=NULL; }            returnXHR; }    functionSave () {varXHR =getxmlhttprequest (); Xhr.open ("Post", "Http://127.0.0.1:8080/test/test.do"); vardata = "Name=mikan&address=street ...";            Xhr.send (data); Xhr.onreadystatechange=function() {                     if(Xhr.readystate = = 4 && xhr.status = 200) {alert ("Returned:" +xhr.responsetext);  }            }; }  

The request header is shown by Chrome's developer tool as follows:

 requesturl:http:// 127.0.0.1:8080/test/ Test.do  request method:post Status Code:  200  OK Request Headers Accept:  */*   ACCEPT-ENCODING:GZIP,DEFLATE,SDCH accept-language:zh-cn,zh;q=0.8,en;q=0.6 alexatoolbar-alx_ns_ph: alexatoolbar/alxg-3.2 connection:keep-alive content-length:28 content-type:text/plain;charset=utf-8 Cookies: Jsessionid=c40c7823648e952e7c6f7d2e687a0a89 host:127.0.0.1:8080 origin:http://127.0.0.1:8080 Referer:http:// 127.0.0.1:8080/test/index.jsp user-agent:mozilla/5.0 (Windows NT 6.1) applewebkit/537.36 (khtml, like Gecko) chrome/ 33.0.1750.149 safari/537.36 Request Payload name=mikan&address=street Response Headers content-length:2 Dat E:sun, 11:49:23 GMT server:apache-coyote/1.1  

Note The requested Content-type is Text/plain;charset=utf-8, and the request form parameter is in Requestpayload.

Then the servlet passed Request.getparameter (name) is empty. Why is it? And how should such parameters be obtained?

In order to understand this problem, looked up some information, also read the Tomcat7.0.53 about the request parameter processing source code, finally figured out what is going on.

When an HTTP post form requests a commit, the content-type used is application/x-www-form-urlencoded, and the POST request that uses the native AJAX does not specify the request header Requestheader, The default content-type used is text/plain;charset=utf-8.

Because Tomcat has "special handling" for Content-type multipart/form-data (file upload) and application/x-www-form-urlencoded (POST request). Here's a look at the related processing code.

The implementation class for Tomcat's HttpServletRequest class is org.apache.catalina.connector.Request (actually org.apache.coyote.Request), and its method for processing request parameters is PROTECTE d void Parseparameters (), this method for Content-type multipart/form-data (file upload) and application/ The processing code for the x-www-form-urlencoded (POST request) is as follows:

protectedvoid parseparameters () {//omit part of the code ...Parameters.handlequeryparameters ();//here is the processing of the parameters in the URL//omit part of the code ...           if("Multipart/form-data". Equals (ContentType)) {//here is the processing file upload requestParseparts (); Success=true; return; }                if(! ("application/x-www-form-urlencoded". Equals (ContentType))) {//if the non-POST request is returned directly, it is no longer processedSuccess =true; return; }             //The following code is the processing of the POST request parameters//omit part of the code ...           Try {                  if(Readpostbody (FormData, len)! = len) {//read request body Data                    return; }             } Catch(IOException e) {//Client Disconnect                if(Context.getlogger (). isdebugenabled ()) {Context.getlogger (). Debug ( Sm.getstring ("Coyoterequest.parseparameters"), E); }                  return; } parameters.processparameters (FormData,0, Len);//handle the POST request parameter and put it in Requestparameter map (that is, Request.getparametermap gets the Map,request.getparameter (name) Also obtained from this map)//omit part of the code ...}        protected intReadpostbody (byteBody[],intlen)throwsIOException {intOffset = 0;  Do {             intInputlen = GetStream (). Read (body, offset, Len-offset); if(Inputlen <= 0) {                  returnoffset; } offset+=Inputlen; }  while((Len-offset) > 0); returnLen; }  

As can be seen from the above code, Content-type is not a application/x-www-form-urlencoded POST request is not to read the request body data and the corresponding parameter processing,

The form data is not parsed to be placed in the request parameter map. So through Request.getparameter (name) is not available.

So how do we get the arguments that are submitted?

Of course it is the most primitive way to read the input stream to get it, as shown below:

privatestring getrequestpayload (httpservletrequest req) {STRINGBUILDERSB=NewStringBuilder (); Try(Bufferedreaderreader =Req.getreader ();) {                     Char[]buff =New Char[1024];                     Intlen;  while(len = reader.read (buff))! =-1) {sb.append (buff,0, Len); }            }Catch(IOException e) {e.printstacktrace ();  } returnsb.tostring (); }  

Of course, the POST request setting up application/x-www-form-urlencoded can also be obtained in this way.

Therefore, when using the native Ajax POST request, you need to explicitly set the request Header, which is:

Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");  

In addition, if I use jquery, I use 1.11.0 this version of the original test, $.ajax POST request is not required to explicitly set the request header, the other version I did not personally tested.

It is believed that the version after 1.11.0 is also not required to be set. But it doesn't have to be before. This has not been tested.

Recently in Reading, really understand, why the server will be the form submission and file upload do special processing, because the form submission data is the way of name value pairs, and Content-type is application/x-www-form-urlencoded, The file upload server needs special processing, the normal POST request (Content-type is not application/x-www-form-urlencoded) data format is not fixed, not necessarily the way of the name value pairs, so the server can not know the specific processing method, Therefore, parsing can only be done by acquiring the original data stream.

jquery sets Content-type to application/x-www-form-urlencoded when executing a POST request, so the server can parse correctly, and when using native AJAX requests, If the settings are not displayed Content-type, then the default is Text/plain, then the server does not know how to parse the data, so only by acquiring the original data stream to parse the request data.

Good article here to collect, the original address: http://blog.csdn.net/mhmyqn/article/details/25561535

How the parameters in the AJAX POST request are obtained in the servlet as form data and request payload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.