4

I am sending a POST request to my localhost Tomcat 8.0 Servlet 3.1 web application but request.getParameter("") returns me null.

This is how I make my request. Using PostMan

I am using PostMan to perform my POST request. And on the java side, I am calling request.getParameter("code") and this gives me null. Same goes for qwe field. I am not using any framework. It's raw servlets. This is only a back-end so it's all about handling the data and responding to client.

If I use "x-www-form-urlencoded", I am able to retrieve the parameters through getParameter() call but I still want to know why I am not able to get form-data.

Thanks.

6
  • It's been a while but, I am pretty sure the form-data method stores the request content in the body of the request, meaning you'd have to get it using a Reader or InputStream. Commented Aug 29, 2017 at 19:38
  • @cjstehno Yes, getReader() 's readLine() method gives me some data and I am able to see my parameter there but I cannot extract it because it has boundary string and needs to be handled separately (from what I've read). But people say this was handled in Servlet 3.0 and above. I am using 3.1 and I still can't get it. Any suggestions? Commented Aug 29, 2017 at 19:40
  • I cannot use getPart("") method to get the file from the form data either. Commented Aug 29, 2017 at 19:52
  • Yes it would be multipart data and you'd need to use something like the JavaMail multipart library to get it (or the Apache FileUpload API) both of which have multipart implementations that will handle http multipart request content. In your case though, the contained data should just be the bytes of a string of text formatted as a multipart content payload. Commented Aug 29, 2017 at 19:58
  • @cjstehno What about when I am not sending a file but only string values. Are they still handled as multipart data? How does one access form-data from a servlet? Commented Aug 29, 2017 at 20:00

2 Answers 2

1

Thanks to @cjstehno,

When he said "form-data" was actually a multipart data, then I attempted to read it as multipart data but taking isFormField() method in mind to distinguish between file and parameter. So from a raw servlet, one can read form-data through the code below. From the performance view, I am pretty sure that this might be improved.

try {
     ServletFileUpload upload = new ServletFileUpload();
     FileItemIterator iter = upload.getItemIterator(request);

     while (iter.hasNext()) {
          FileItemStream item = iter.next();
          String name = item.getFieldName();

          if (item.isFormField()) {
               String value = Streams.asString(item.openStream());
          }
     }          
 } catch (Exception ex) {}
Sign up to request clarification or add additional context in comments.

2 Comments

For some reason, when I wrap a request, I can't get parameter even though content type was x-www-form-urlencoded. I had to change client code to always send form data with content type of form-data
Update: I was using custom ServletInputStream implementation and forgot to set isFinished and isReady.
0

If you are developing a login page and fetching values using from JavaScript file

public class LoginCredentials extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain"); // Set content type to plain text or application/json as needed

        try {
            // Check if the request is multipart/form-data
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            
            if (isMultipart) {
                // Create a new ServletFileUpload instance
                ServletFileUpload upload = new ServletFileUpload();
                // Parse the request to get the list of FileItemStream objects
                FileItemIterator iter = upload.getItemIterator(request);

                // Iterate over the items
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    String fieldName = item.getFieldName();
                    InputStream inputStream = item.openStream();

                    if (item.isFormField()) {
                        // This is a regular form field
                        String value = IOUtils.toString(inputStream, "UTF-8");
                        
                        if ("user".equals(fieldName)) {
                            // Assuming 'user' is the name attribute of the username input field
                            String username = value;
                            System.out.println("Username: " + username);
                        } else if ("pwd".equals(fieldName)) {
                            // Assuming 'pwd' is the name attribute of the password input field
                            String password = value;
                            System.out.println("Password: " + password);
                        }
                    }
                }

                // Here you can add your authentication logic based on username and password
                // For demonstration purposes, let's just send a success message back
                response.getWriter().write("Login successful");
            } else {
                response.getWriter().write("Multipart form data expected");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("Error occurred while processing login");
        }
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.