javaservletshttp-postgetparameter

How to get values of getParameterValues in the order they are sent?


I am sending registration form data through HttpPost method to Servlet and get this data by getParameterValues.

No problem with getting data, but I get the data in random order. I want that at servlet I get the data in order of how they are sent. I try to solve this by reading in internet but nothing can help. I am posting my servlet code here.

response.setContentType("text/html");
    ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
    Enumeration paramNames = request.getParameterNames();
    String params[] = new String[7];
    int i=0;

    while(paramNames.hasMoreElements())
    {
        String paramName = (String) paramNames.nextElement();
        System.out.println(paramName);


        String[] paramValues = request.getParameterValues(paramName);
        params[i] = paramValues[0];

        System.out.println(params[i]);

        i++;
    }

I get the output like this

5_Country
United States
4_Password
zxcbbnm
1_Lastname
xyz
0_Firstname
abc
3_Email
abc@xyz.com
6_Mobile
1471471471
2_Username
abcd

I want 0_Firstname first then 1_Lastname then 2_Username like that, because I want to insert this data in database. Here 0,1,2...I wrote just for indicate that I want value in this order.


Solution

  • You won't get the parameter names in order by using request.getParameterNames(); .

    You can either use

    String [] parameterNames =  new String[]{"param1","param2","param3"};
    
    for(String param : parameterNames){
     System.out.println(param);
    }
    

    where parameterNames conains sequence in which you want your parameters. You can even configure it and read sequence from a config file.

    OR

    You can use

     request.getQueryString() to get the QueryString, while using GET Method
    

    OR

    You can use

     request.getInputStream() to get the QueryString, while using POST Method
     and parse the raw data to get the Query string.
    

    After getting query string , you can split and use the way you want.