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

后端 未结 1 1364
春和景丽
春和景丽 2020-12-31 20:52

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, G

相关标签:
1条回答
  • 2020-12-31 21:36

    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.

    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 {}
    

    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?

    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);
    

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

    See also:

    • How to use Servlets and Ajax?
    • sending a file as multipart through xmlHttpRequest
    0 讨论(0)
提交回复
热议问题