Pages

Thursday, November 11, 2010

request.getParameterMap()

  
The getParameterMap() returns a Map that has Strings as keys and String[] as values. That's so you can have ?x=1&x=2&x=3 in your URL query string. The keys in the Map must be unique but there can be multiple values for each key.

So.. when you pull a value out of a Map created by the getParameterMap() method you must cast it to a String[] or else you'll get the value's location in memory instead of it's actual value. If you're writing the code and know for a fact that you'll always have only one value for each param then you can just use yourVar[0] but if there may be multiple values for each key then you'll need to loop over each value array.


Code :
Map params = request.getParameterMap();
Iterator i = params.keySet().iterator();

while ( i.hasNext() )
  {
    String key = (String) i.next();
    String value = ((String[]) params.get( key ))[ 0 ];
  }

Code :

Map param_map = request.getParameterMap();
if (param_map == null)
    throw new ServletException(
      "getParameterMap returned null in: " + getClass().getName());

 //iterate through the java.util.Map and display posted parameter values
//the keys of the Map.Entry objects ae type String; the values are type String[],
//or String array
Iterator iterator = param_map.entrySet().iterator();
while(iterator.hasNext()){
    Map.Entry me = (Map.Entry)iterator.next();
    out.println(me.getKey() + ": ");
    String[] arr = (String[]) me.getValue();
    for(int i=0;i<arr.length;i++){
      out.println(arr[i]);
      //print commas after multiple values, 
      //except for the last one
      if (i > 0 && i != arr.length-1)
        out.println(", ");}//end for
        out.println("<br><br>");
    }//end while




refer: http://snippets.dzone.com/posts/show/3491     http://www.java2s.com/Code/Java/Servlets/PostHandler.htm

No comments:

Post a Comment