How to obtain the form data and request payload in the servlet in the Ajax POST request

Source: Internet
Author: User
Tags webp

In an HTTP request, if it is a GET request, the number of tokens in the form of name = Value & name1 = value1 is appended to the URL. If it is a POST request, then, the number of form parts is in the Request body in the form of name = Value & name1 = value1. Using Chrome's developer tools, you can see the following (here is a readable form, not a real HTTP request format ):

GET request:

RequestURL:http://127.0.0.1:8080/test/test.do?name=mikan&address=streetRequest Method:GETStatus Code:200 OK Request HeadersAccept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Accept-Encoding:gzip,deflate,sdchAccept-Language:zh-CN,zh;q=0.8,en;q=0.6AlexaToolbar-ALX_NS_PH:AlexaToolbar/alxg-3.2Connection:keep-aliveCookie:JSESSIONID=74AC93F9F572980B6FC10474CD8EDD8DHost:127.0.0.1:8080Referer:http://127.0.0.1:8080/test/index.jspUser-Agent:Mozilla/5.0 (Windows NT 6.1)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36 Query String Parametersname:mikanaddress:street Response HeadersContent-Length:2Date:Sun, 11 May 2014 10:42:38 GMTServer:Apache-Coyote/1.1

POST request:

RequestURL:http://127.0.0.1:8080/test/test.doRequest Method:POSTStatus Code:200 OK Request HeadersAccept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Accept-Encoding:gzip,deflate,sdchAccept-Language:zh-CN,zh;q=0.8,en;q=0.6AlexaToolbar-ALX_NS_PH:AlexaToolbar/alxg-3.2Cache-Control:max-age=0Connection:keep-aliveContent-Length:25Content-Type:application/x-www-form-urlencodedCookie:JSESSIONID=74AC93F9F572980B6FC10474CD8EDD8DHost:127.0.0.1:8080Origin:http://127.0.0.1:8080Referer:http://127.0.0.1:8080/test/index.jspUser-Agent:Mozilla/5.0 (Windows NT 6.1)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36 Form Dataname:mikanaddress:street Response HeadersContent-Length:2Date:Sun, 11 May 2014 11:05:33 GMTServer:Apache-Coyote/1.1

Note that the Content-Type of the POST request is application/X-WWW-form-urlencoded, and the number of records is in the Request body, that is, the form data in the request above.

In servlet, the number of parameters in the form can be obtained in the form of request. getparameter (name.

Assume that the native Ajax POST request is used:

         function getXMLHttpRequest() {                   var xhr;                   if(window.ActiveXObject) {                            xhr= new ActiveXObject("Microsoft.XMLHTTP");                   }else if (window.XMLHttpRequest) {                            xhr= new XMLHttpRequest();                   }else {                            xhr= null;                   }                   return xhr;         }          function save() {                   var xhr = getXMLHttpRequest();                   xhr.open("post","http://127.0.0.1:8080/test/test.do");                   var data = "name=mikan&address=street...";                   xhr.send(data);                   xhr.onreadystatechange= function() {                            if(xhr.readyState == 4 && xhr.status == 200) {                                     alert("returned:"+ xhr.responseText);                            }                   };         }

 

You can see the request header in Chrome's developer tools as follows:

RequestURL:http://127.0.0.1:8080/test/test.doRequest Method:POSTStatus Code:200 OK Request HeadersAccept:*/*Accept-Encoding:gzip,deflate,sdchAccept-Language:zh-CN,zh;q=0.8,en;q=0.6AlexaToolbar-ALX_NS_PH:AlexaToolbar/alxg-3.2Connection:keep-aliveContent-Length:28Content-Type:text/plain;charset=UTF-8Cookie:JSESSIONID=C40C7823648E952E7C6F7D2E687A0A89Host:127.0.0.1:8080Origin:http://127.0.0.1:8080Referer:http://127.0.0.1:8080/test/index.jspUser-Agent:Mozilla/5.0 (Windows NT 6.1)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36 Request Payloadname=mikan&address=street Response HeadersContent-Length:2Date:Sun, 11 May 2014 11:49:23 GMTServer:Apache-Coyote/1.1

Note that the requested Content-Type is text/plain; charset = UTF-8, and the number of request form records is in requestpayload.

In servlet, request. getparameter (name) is null. Why? How can we get this number of shards?

In order to clarify this problem, I checked some information and read the source code of tomcat7.0.53 for processing the number of requests. Finally, I figured out what was going on.

When an http post form request is submitted, the Content-Type used is application/X-WWW-form-urlencoded. the post request using native Ajax assumes that the request header requestheader is not specified, the default Content-Type is text/plain; charset = UTF-8.

Because Tomcat performs "special processing" on Content-Type multipart/form-data (File Upload) and application/X-WWW-form-urlencoded (POST request ". Let's take a look at the relevant processing code.

The implementation class of Tomcat's httpservletrequest class is Org. apache. catalina. connector. request (actually Org. apache. coyote. request), and its method for processing the number of request shards is protected void parseparameters (). In this method, Content-Type multipart/form-data (File Upload) and the application/X-WWW-form-urlencoded (POST request) Processing code is as follows:

Protectedvoid parseparameters () {// omitting some code ...... parameters. handlequeryparameters (); // handle the number of workers in the URL // omit some code ...... if ("multipart/form-data ". equals (contenttype) {// here is the parseparts (); success = true; return ;}if (! ("Application/X-WWW-form-urlencoded ". equals (contenttype) {// assume that a non-POST request is returned directly and success = true; return;} is not processed ;} // The following code processes the number of post requests. // some codes are omitted ...... try {If (readpostbody (formdata, Len )! = Len) {// read the 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); // process the number of POST request shards and put it in requestparameter map (request. the map obtained by getparametermap, request. getparameter (name) is also obtained from this map) // omitting some code ......} protected int readpostbody (byte body [], int Len) throws ioexception {int offset = 0; do {int inputlen = getstream (). read (body, offset, len-offset); If (inputlen <= 0) {return offset;} Offset + = inputlen;} while (LEN-offset)> 0 ); return Len ;}

From the code above, we can see that the POST request does not read the Request body data and process the corresponding number of shards. That is, after the form data is parsed, it is placed in the Request Parameter map (request. the map obtained by getparametermap, request. getparameter (name) is also obtained from this map ). Therefore, request. getparameter (name) cannot be obtained.

How can we obtain the number of shards submitted in this way?

Of course, the original method is used to read the input stream, as shown in the following figure:

         privateString getRequestPayload(HttpServletRequest req) {                   StringBuildersb = new StringBuilder();                   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, post requests with application/X-WWW-form-urlencoded configured can also be obtained in this way.

Therefore, when using a native Ajax POST request, you need to clearly set the request header, that is:

xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

In addition, if jquery is used, I will use the 1.11.0 version number for testing. The $. Ajax POST request does not need to understand how to set this request header. I have not personally tried other versions. It is believed that the version number after 1.11.0 does not need to be set. It's just that some of them are not necessarily the same. This has not been retried.

How to obtain the form data and request payload in the servlet in the Ajax POST request

Related Article

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.