Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of request.getParameterNames()

How do I get all the parameterNames in an HTML form in the same sequence?

Example:

  • If the form contains FirstName, LastNameand Age

  • The output should appear exatcly in the same sequence

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);
}
like image 935
jcdmb Avatar asked Jan 19 '11 09:01

jcdmb


1 Answers

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 ?

like image 70
Manuel Salvadores Avatar answered Oct 07 '22 07:10

Manuel Salvadores