Question

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

Was it helpful?

Solution

I managed to identify the problem. Because there is so much chatter from JDK 1.5+ and talk of getParameterMaps() method for 1.5, info on how 1.4 handles form post data was scarce and ambiguous. (Please post a comment if you find something that is specific for 1.4).

Pre-1.5 you have to manually get the form data via getInputStream, and then parse it out. I found this method, (posted below), from the java sun site that does a nice job using a Hashtable. I had to make a minor mod for deprecated methods. But seems to work quite robustly, "out of the box", so you should able to just cut-n-paste. I know it's "old tech" but I thought it worthwhile for those who may be in the same situation as me who are stuck on solving (what seems to be) straight forward problems.

public Hashtable parsePostData(int length, ServletInputStream instream) {
                String valArray[] = null;
                int inputLen, offset;
                byte[] postedBytes = null;
                boolean dataRemaining=true;
                String postedBody;
                Hashtable ht = new Hashtable();
                //Vector paramOrder = new Vector(10);
                StringBuffer sb = new StringBuffer();

                if (length <=0) {
                  return null;
                }
                postedBytes = new byte[length];
                try {
                   offset = 0;
                   while(dataRemaining) {
                     inputLen = instream.read (postedBytes, offset, length - offset);
                     if (inputLen <= 0) {
                       throw new IOException ("read error");
                     }
                     offset += inputLen;
                     if((length-offset) ==0) {
                       dataRemaining=false;
                     }
                   }
                } catch (IOException e) {
                  System.out.println("Exception ="+e);
                  return null;
                }

                postedBody = new String (postedBytes);
                StringTokenizer st = new StringTokenizer(postedBody, "&");

                String key=null;
                String val=null;

                while (st.hasMoreTokens()) {
                  String pair = (String)st.nextToken();
                  int pos = pair.indexOf('=');
                  if (pos == -1) {
                    throw new IllegalArgumentException();
                  }
                  try {
                     key = URLDecoder.decode(pair.substring(0, pos),"UTF8");
                     val = java.net.URLDecoder.decode(pair.substring(pos+1,pair.length()),"UTF8");
                  } catch (Exception e) {
                     throw new IllegalArgumentException();
                  }
                  if (ht.containsKey(key)) {
                    String oldVals[] = (String []) ht.get(key);
                    valArray = new String[oldVals.length + 1];
                    for (int i = 0; i < oldVals.length; i++) {
                       valArray[i] = oldVals[i];
                    }
                    valArray[oldVals.length] = val;
                  } else {
                    valArray = new String[1];
                    valArray[0] = val;
                  }
                  ht.put(key, valArray);
                  String sValues = "";
                  for(int i=0;i<valArray.length;i++) {
                      if (0<i) {
                          sValues+=",";
                      }
                      sValues = valArray[i];
                  }
                  System.out.println("Form data field " + key + ":" +sValues); 
                  //paramOrder.addElement(key);
                }
                return ht;
              }

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top