ajaxhtmlservletsxmlhttprequestform-data

HTML5 FormData returns null in Java Servlet request.getParameter()


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 code

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 code (both parameters return null)

out.println("Hello! "+ request.getParameter("firstName")+ " "+ request.getParameter("lastName")+ ", thanks for sending your feedback." );

Google Chrome Console

Content-Disposition: form-data; name="firstName"
XYZ
Content-Disposition: form-data; name="lastName"
ABC

Solution

  • The HTML5 FormData API sends a multipart/form-data request. It was initially designed to be able to upload files by Ajax, with XMLHttpRequest level 2. Uploading files wasn't possible with the first level of XMLHttpRequest.

    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 explicitly annotate your servlet class with @MultipartConfig so that you can get them by request.getParameter().

    @WebServlet
    @MultipartConfig
    public class YourServlet extends HttpServlet {}
    

    Alternatively, if you actually don't need to upload files at all, but merely need to send plain strings, then 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);
    

    This way you don't need @MultipartConfig on your servlet anymore.

    See also: