HTML5 FormData 在 Java Servlet request.getParameter() 中返回 null

2022-01-15 00:00:00 xmlhttprequest html ajax form-data servlets

我的观点是 HTML 5.我正在使用 FormData 将 AJAX 2 POST 发送到 Servlet.在 servlet 内部,我试图读取请求参数.我看不到任何参数.但是,Google Chrome 开发控制台会显示请求负载.我怎样才能在 Servlet 代码中得到相同的结果?任何帮助将不胜感激.这是代码.

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 代码(两个参数都返回 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 发送 multipart/form-data 请求.它最初设计为能够通过 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() 默认只识别 application/x-www-form-urlencoded 请求.但是您正在发送 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.有关这两种方法的更详细答案,请参阅:如何使用 JSP/Servlet 将文件上传到服务器?

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?

如果您根本不需要上传文件,请改用标准"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 多部分发送文件

相关文章