最近做項目時,發(fā)現(xiàn)手機客戶端通過http協(xié)議post方式上傳數(shù)據(jù)到服務端,在服務器端通過request.getInputStream()能獲取到相應的數(shù)據(jù),但用request.getParameter()卻獲取不到數(shù)據(jù)。這是怎么回事呢,后來發(fā)現(xiàn)這種情況跟form表單的屬性 enctype有關系。
HTML中的form表單有一個關鍵屬性 enctype=application/x-www-form-urlencoded 或multipart/form-data。
1、enctype="application/x-www-form-urlencoded"是默認的編碼方式,當以這種方式提交數(shù)據(jù)時,HTTP報文中的內容是:
Html代碼
<span style="font-size: small;">POST /post_test.php HTTP/1.1 Accept-Language: zh-CN User-Agent: Mozilla/4.0 Content-Type: application/x-www-form-urlencoded Host: 192.168.12.102 Content-Length: 42 Connection: Keep-Alive Cache-Control: no-cache title=test&content=%B3%AC%BC%B6%C5%AE%C9%FA&submit=post+article </span> Servlet的API提供了對這種編碼方式解碼的支持,只需要調用ServletRequest 類中的getParameter()方法就可以得到表單中提交的數(shù)據(jù)。
2、在傳輸大數(shù)據(jù)量的二進制數(shù)據(jù)時,必須將編碼方式設置成enctype="multipart/form-data",當以這種方式提交數(shù)據(jù)時,HTTP報文中的內容是:
Html代碼
<span style="font-size: small;">POST /post_test.php?t=1 HTTP/1.1 Accept-Language: zh-CN User-Agent: Mozilla/4.0 Content-Type: multipart/form-data; boundary=---------------------------7dbf514701e8 Accept-Encoding: gzip, deflate Host: 192.168.12.102 Content-Length: 345 Connection: Keep-Alive Cache-Control: no-cache -----------------------------7dbf514701e8 Content-Disposition: form-data; name="title" test -----------------------------7dbf514701e8 Content-Disposition: form-data; name="content" .... -----------------------------7dbf514701e8 Content-Disposition: form-data; name="submit" post article -----------------------------7dbf514701e8--</span> 如果以這種方式提交數(shù)據(jù)就要用request.getInputStream()或request.getReader()來獲取提交的數(shù)據(jù) ,用 request.getParameter()是獲取不到提交的數(shù)據(jù)的。
最后注意request.getParameter()、request.getInputStream()、request.getReader()這三種方法是有沖突的,因為流只能被讀一次。比如: 當form表單內容采用enctype=application/x-www-form-urlencoded編碼時,先通過調用request.getParameter()方法獲取數(shù)據(jù)后,再調用request.getInputStream()或request.getReader()已經獲取不到流中的內容了,因為在調用 request.getParameter()時系統(tǒng)可能對表單中提交的數(shù)據(jù)以流的形式讀了一次,反之亦然。
當form表單內容采用enctype=multipart/form-data編碼時,調用request.getParameter()獲取不到數(shù)據(jù),即使已經調用了request.getParameter()方法也可以再通過調用request.getInputStream()或request.getReader()獲取表單中的數(shù)據(jù),但request.getInputStream()和request.getReader()在同一個響應中是不能混合使用的,如果混合使用會拋異常的。
|
新聞熱點
疑難解答