問題描述
我的觀點是 HTML 5.我正在使用 FormData 將 AJAX 2 POST 發(fā)送到 Servlet.在 servlet 內(nèi)部,我試圖讀取請求參數(shù).我看不到任何參數(shù).但是,Google Chrome 開發(fā)控制臺會顯示請求負(fù)載.我怎樣才能在 Servlet 代碼中得到相同的結(jié)果?任何幫助將不勝感激.這是代碼.
My view is HTML 5. I'm using FormData to make a AJAX 2 POST to a Servlet. Inside the servlet i'm trying to read request parameters. I can't see any parameters. However, Google Chrome Dev console shows the request payload. How can I get the same in Servlet code? Any help will be appreciated. Here's the code.
JS代碼
var xhr = new XMLHttpRequest();
var formData = new FormData();
formData.append('firstName', 'ABC');
formData.append('lastName', 'XYZ');
xhr.open("POST", targetLocation, true);
xhr.send(formData);
Servlet 代碼(兩個參數(shù)都返回 null
)
Servlet code (both parameters return null
)
out.println("Hello! "+ request.getParameter("firstName")+ " "+ request.getParameter("lastName")+ ", thanks for sending your feedback." );
谷歌瀏覽器控制臺
Content-Disposition: form-data; name="firstName"
XYZ
Content-Disposition: form-data; name="lastName"
ABC
推薦答案
HTML5 FormData
API 發(fā)送 multipart/form-data
請求.它最初設(shè)計為能夠通過 ajax 上傳文件,新版本 2 XMLHttpRequest
.以前的版本無法上傳文件.
The HTML5 FormData
API sends a multipart/form-data
request. It's initially designed to be able to upload files by ajax, with the new version 2 XMLHttpRequest
. Uploading files wasn't possible with the previous version.
request.getParameter()
默認(rèn)只識別 application/x-www-form-urlencoded
請求.但是您正在發(fā)送 multipart/form-data
請求.您需要使用 @MultipartConfig 注釋您的 servlet 類
以便你可以通過 request.getParameter()
獲取它們.
The request.getParameter()
by default recognizes application/x-www-form-urlencoded
requests only. But you're sending a multipart/form-data
request. You need to annotate your servlet class with @MultipartConfig
so that you can get them by request.getParameter()
.
@WebServlet
@MultipartConfig
public class YourServlet extends HttpServlet {}
或者,如果您還沒有使用 Servlet 3.0,請使用 Apache Commons FileUpload.有關(guān)這兩種方法的更詳細(xì)答案,請參閱:如何使用 JSP/Servlet 將文件上傳到服務(wù)器?
Or, when you're still not on Servlet 3.0 yet, use Apache Commons FileUpload. For a more detailed answer on both approaches, see this: How to upload files to server using JSP/Servlet?
如果您根本不需要上傳文件,請改用標(biāo)準(zhǔn)"XMLHttpRequest
方法.
If you don't need to upload files at all, use the "standard" XMLHttpRequest
approach instead.
var xhr = new XMLHttpRequest();
var data = "firstName=" + encodeURIComponent(firstName)
+ "&lastName=" + encodeURIComponent(lastName);
xhr.open("POST", targetLocation, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
這樣你的servlet就不再需要@MultipartConfig
了.
This way you don't need @MultipartConfig
on your servlet anymore.
- 如何使用 Servlet 和 Ajax?
- 通過 xmlHttpRequest 多部分發(fā)送文件
這篇關(guān)于HTML5 FormData 在 Java Servlet request.getParameter() 中返回 null的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!