HTTP請求中,若是是get請求,那麼表單參數以name=value&name1=value1的形式附到url的後面,若是是post請求,那麼表單參數是在請求體中,也是以name=value&name1=value1的形式在請求體中。經過chrome的開發者工具能夠看到以下(這裏是可讀的形式,不是真正的HTTP請求協議的請求格式):html
get請求:jquery
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 May 2014 10:42:38 GMT Server:Apache-Coyote/1.1
附圖:web
Post請求:ajax
RequestURL:http://127.0.0.1:8080/test/test.do Request Method:POST 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 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 Headers Content-Length:2 Date:Sun, 11 May 2014 11:05:33 GMT Server:Apache-Coyote/1.1
附圖:chrome
這裏要注意post請求的Content-Type爲application/x-www-form-urlencoded,參數是在請求體中,即上面請求中的Form Data。apache
在servlet中,能夠經過request.getParameter(name)的形式來獲取表單參數。json
而若是使用原生AJAX POST請求的話:數組
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); } }; }
經過chrome的開發者工具看到請求頭以下:服務器
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 Cookie: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 Date:Sun, 11 May 2014 11:49:23 GMT Server:Apache-Coyote/1.1
注意請求的Content-Type爲text/plain;charset=UTF-8,而請求表單參數在RequestPayload中。app
那麼servlet中經過request.getParameter(name)倒是空。爲何呢?而這樣的參數又該怎麼樣獲取呢?
爲了搞明白這個問題,查了些資料,也看了Tomcat7.0.53關於請求參數處理的源碼,終於搞明白了是怎麼回事。
HTTP POST表單請求提交時,使用的Content-Type是application/x-www-form-urlencoded,而使用原生AJAX的POST請求若是不指定請求頭RequestHeader,默認使用的Content-Type是text/plain;charset=UTF-8。
因爲Tomcat對於Content-Type multipart/form-data(文件上傳)和application/x-www-form-urlencoded(POST請求)作了「特殊處理」。下面來看看相關的處理代碼。
Tomcat的HttpServletRequest類的實現類爲org.apache.catalina.connector.Request(其實是org.apache.coyote.Request),而它對處理請求參數的方法爲protected void parseParameters(),這個方法中對Content-Type multipart/form-data(文件上傳)和application/x-www-form-urlencoded(POST請求)的處理代碼以下:
protectedvoid parseParameters() { //省略部分代碼...... parameters.handleQueryParameters();// 這裏是處理url中的參數 //省略部分代碼...... if ("multipart/form-data".equals(contentType)) { // 這裏是處理文件上傳請求 parseParts(); success = true; return; } if(!("application/x-www-form-urlencoded".equals(contentType))) {// 這裏若是是非POST請求直接返回,再也不進行處理 success = true; return; } //下面的代碼纔是處理POST請求參數 //省略部分代碼...... try { if (readPostBody(formData, len)!= len) { // 讀取請求體數據 return; } } catch (IOException e) { // Client disconnect if(context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"),e); } return; } parameters.processParameters(formData, 0, len); // 處理POST請求參數,把它放到requestparameter map中(即request.getParameterMap獲取到的Map,request.getParameter(name)也是從這個Map中獲取的) // 省略部分代碼...... } 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; }
從上面代碼能夠看出,Content-Type不是application/x-www-form-urlencoded的POST請求是不會讀取請求體數據和進行相應的參數處理的,即不會解析表單數據來放到request parameter map中。因此經過request.getParameter(name)是獲取不到的。
那麼這樣提交的參數咱們該怎麼獲取呢?
固然是使用最原始的方式,讀取輸入流來獲取了,以下所示:
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(); }
或者能夠這樣獲取request payload 的請求參數:
//後臺接收方式: InputStream inputStream = request.getInputStream(); byte[] buff = new byte[1024]; int len = -1; while (-1 != (len = inputStream.read(buff))) { // 將字節數組轉換爲字符串,而且設置爲「UTF-8」格式編碼(否則會出現亂碼) String res = new String(buff, 0, len,"UTF-8"); jsonObject = new org.json.JSONObject(res); int offset = jsonObject.getInt("offset"); int limit = jsonObject.getInt("limit"); }
固然,設置了application/x-www-form-urlencoded的POST請求也能夠經過這種方式來獲取。
因此,在使用原生AJAX POST請求時,須要明確設置Request Header,即:
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
另外,若是使用jquery,我使用1.11.0這個版原本測試,$.ajax post請求是不須要明確設置這個請求頭的,其餘版本的本人沒有親自測試過。相信在1.11.0以後的版本也是不須要設置的。不過以前有的就不必定了。這個沒有測試過。
2015-04-17後記:
最近在看書時才真正搞明白,服務器爲何會對錶單提交和文件上傳作特殊處理,由於表單提交數據是名值對的方式,且Content-Type爲application/x-www-form-urlencoded,而文件上傳服務器須要特殊處理,普通的post請求(Content-Type不是application/x-www-form-urlencoded)數據格式不固定,不必定是名值對的方式,因此服務器沒法知道具體的處理方式,因此只能經過獲取原始數據流的方式來進行解析。
jquery在執行post請求時,會設置Content-Type爲application/x-www-form-urlencoded,因此服務器可以正確解析,而使用原生ajax請求時,若是不顯示的設置Content-Type,那麼默認是text/plain,這時服務器就不知道怎麼解析數據了,因此才只能經過獲取原始數據流的方式來進行解析請求數據。