DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Retrieving All Parameters To A Java Servlet

02.10.2007
| 35863 views |
  • submit to reddit
        // 
// Ref: http://forum.java.sun.com/thread.jspa?threadID=405328&messageID=2184836
// 
// 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.
// 

    Map params = request.getParameterMap();
    Iterator i = params.keySet().iterator();
    
    while ( i.hasNext() )
      {
        String key = (String) i.next();
        String value = ((String[]) params.get( key ))[ 0 ];
      }