Issue
How do I get all the parameterNames
in an HTML form in
the same sequence?
Example:
If the form contains
FirstName
,LastName
andAge
I have tried using the following but this shifts the order of the output:
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
out.print(paramName);
}
Solution
I don't think there's nothing in the HTTP spec that forces browsers to send parameters in the order they appear in the form. You can work it around by prefixing a number to the name of the parameter like:
FirstName --> 0_FirstName
LastName --> 1_LastName
...
After that you could basically order the elements by the prefix. It is an ugly solution but it is the only way to do it. Something like:
// Assuming you fill listOfParameters with all the parameters
Collections.sort(listOfParameters, new Comparator<String>() {
int compare(String a,String b) {
return Integer.getInt(a.substring(0,a.indexOf("_"))) -
Integer.getInt(a.substring(0,b.indexOf("_")))
}
});
for (String param : listOfParameters) {
// traverse in order of the prefix
}
By the way - does it really matters the order in which you receive the parameters ?
Answered By - Manuel Salvadores
Answer Checked By - Gilberto Lyons (JavaFixing Admin)