Ordering of values in HttpServletRequest.getParameterValues()

http, java, servlets

Solution

The javadoc for ServletRequest (v2.5 javadoc) does not mention anything about the ordering of values for that method. As such, I wouldn't rely on the order being preserved.

Update: also checked the spec document for 2.5, contains the following information relating to getParameterValues(). It does not mention anything about ordering with respect to the query string, so I think the behaviour you are seeing is implementation detail, not defined as part of the interface.

The parameters are stored as a set of name-value pairs. Multiple parameter values can exist for any given parameter name. The following methods of the ServletRequest interface are available to access parameters:

- getParameter

- getParameterNames

- getParameterValues

- getParameterMap

The getParameterValues method returns an array of String objects containing all the parameter values associated with a parameter name. The value returned from the getParameter method must be the first value in the array of String objects returned by getParameterValues. The getParameterMap method returns a java.util.Map of the parameter of the request, which contains names as keys and parameter values as map values.

For future reference, the Java Servlet specs can be downloaded from Sun, I mean Oracle's website. You can double check the specific servlet version you're interested in there.

Problem

`HttpServletRequest.getParameterValues()` returns a `String[]` containing all values of a given HTTP request parameter. Does anyone know if the order of the values in this array is guaranteed by specification to by the same as the order which those values were passed through in the request? For example, if I have the GET query string `x=1&x=2&x=3`, am I guaranteed to receive the `String[] {"1", "2", "3"}` when I call `getParameterValues()`? It seems to work in practice, but I can't find anything which specifies that this must be the case, so I'm reluctant to rely on it.

Original source