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

My opinion is HTML 5. I am using FormData to create an AJAX 2 POST for the servlet. Inside the servlet, I am trying to read the request parameters. I do not see any parameters. However, the Google Chrome Dev console shows the request payload. How can I get the same in servlet code? Any help would be appreciated. Here is 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 
+6
source share
1 answer

HTML5 API FormData sends a multipart/form-data request. At first it was designed to download files using ajax, with the new version 2 of XMLHttpRequest . Downloading previous version of files is not possible.

request.getParameter() only recognizes application/x-www-form-urlencoded requests by default. But you are sending a multipart/form-data request. You need to annotate your @MultipartConfig servlet class so you can get them through request.getParameter() .

 @WebServlet @MultipartConfig public class YourServlet extends HttpServlet {} 

Or, if you are not already using Servlet 3.0, use Apache Commons FileUpload. See the following for a more detailed answer to both approaches: How do I upload files to the server using JSP / Servlet?

If you donโ€™t need to upload files at all, use the โ€œstandardโ€ XMLHttpRequest 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 will no longer need @MultipartConfig on your servlet.

See also:

+10
source

Source: https://habr.com/ru/post/914004/


All Articles