This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I wrote a class for one of my servlets to use that accepts a Map object, which it uses to retrieve pre-defined parameters.
I originally wrote it to accept an HttpServletRequest object and then retrieved the desired parameters using request.getParameter. I decided that I wanted to make the class a bit more reusable by changing that HttpServletRequest object to a Map object so it can be used outside of a servlet environment.
My idea was to use the request.getParameterMap() method in my servlet to pass in a map. Well, I suppose I didn't read the documentation close enough, because it turns out that the values in the Map returned by request.getParameterMap() are String arrays, so when I cast the parameters I was retrieving out of the map to (String) it blew up.
My question is, do I have to write something to convert the request parameters to a normal map and not use getParameterMap at all, or is there an intelligent way to determine if the object I'm pulling out of the map is an array, in which case I would just grab the first value in the array?
do I have to write something to convert the request parameters to a normal map
It is a "normal map". Nothing says a Map's values need to be strings. The values are string arrays since each request parameter can have multiple values (see getParameterValues()). If you are sure that your request parameters will all have a single value, it will be safe to just grab the first value. But a better solution may be Anthony's suggestion to make your "consumer" class deal with the String array in a versatile fashion. [ June 22, 2004: Message edited by: Bear Bibeault ]
Sorry, I didn't mean to imply that the Map returned by getParameterMap was not a normal Map. What I really meant to say was: "...do I have to write something to convert the request parameters to a Map with regular Strings (not String arrays)...".
Actually, Anthony's proposed solution is exactly what I was looking for.