How do you access posted form data in a servlet?

angryITguy picture angryITguy · Aug 16, 2011 · Viewed 8.2k times · Source

If I have a servlet running JVM1.4.2, and it is receiving a POST request with form data fields. I use req.getParameterNames() to get, what I would expect, all the query string and form data. However, all I ever get are the querystring parameters.

Literature I am reading from various sources says that getParameterNames() and getParameterValues(String) should be the way to get all query string and posted form data sent by the browser for JDK 1.4. Here is the method I use to extract all the parameters, which I expect would include posted form data :

public Map getParameterMap(HttpServletRequest req) {
        Map params= new HashMap();
        String name = null;
        System.out.println("<< Getting Parameter Map.>>");
        Enumeration enumParams = req.getParameterNames();
        for (; enumParams.hasMoreElements(); ) {
            // Get the name of the request parameter
            name = (String)enumParams.nextElement();

            // Get the value of the request parameters

            // If the request parameter can appear more than once 
            //   in the query string, get all values
            String[] values = req.getParameterValues(name);
            params.put(name, values);
            String sValues = "";
            for(int i=0;i<values.length;i++){
                if(0<i) {
                    sValues+=",";
                }
                sValues +=values[i];
            }
            System.out.println("Param " + name + ": " + sValues);
        }
        System.out.println("<< END >>");
        return params;
    }

This question also agrees with my expectations, but the servlet is not picking up the form data. Obviously I am missing something....

Update: The post data is very straight forward and is not a Multipart form or rich media. Just plain'ol text submitted via an AJAX POST that looks like this in post body

c1=Value%20A&c2=Value%20B&c3=Value%20C

Answer

Ryan Stewart picture Ryan Stewart · Aug 16, 2011

That's true. The getParameterNames(), getParameterValues(), and getParameter() methods are the way to access form data unless it's a multipart form, in which case you'll have to use something like Commons Fileupload to parse the multipart request before all the parameters are accessible to you.

Edit: You're probably not encoding the POST data properly in your AJAX call. POST data must carry a Content-Type of application/x-www-form-urlencoded or else multipart/form-data. If you're sending it as something else, it doesn't qualify as a request parameter, and I expect you'd see the behavior you're describing. The solution you've engineered essentially consists of setting up custom parsing of custom content.