1

我通过 HttpPost 方法向 Servlet 发送注册表单数据,并通过 getParameterValues 获取此数据。

获取数据没问题,但我以随机顺序获取数据。我希望在 servlet 中按发送方式获取数据。我尝试通过在互联网上阅读来解决这个问题,但没有任何帮助。我在这里发布我的 servlet 代码。

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++;
    }

我得到这样的输出

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

我想先 0_Firstname 然后 1_Lastname 然后 2_Username 这样,因为我想将此数据插入数据库中。这里 0,1,2...我写只是为了表明我想要这个顺序的值。

4

2 回答 2

1

试试这个

Enumeration<String> enumParamNames = request.getParameterNames();

转换EnumerationList以便对它们进行排序。

List<String> listParamNames = Collections.list(enumParamNames);

paramNames 在排序之前看起来像这样

[5_Country, 4_Password, 1_Lastname, 0_Firstname, 2_Username, 3_Email]

对列表进行排序Collections.sort(listParamNames);

排序后的 paramNames 将如下所示

[0_Firstname, 1_Lastname, 2_Username, 3_Email, 4_Password, 5_Country]

现在您可以循环使用listParamNames以获取关联的param value

for(String paramName : listParamNames)
{
    System.out.println(paramName);
    System.out.print("\t");

    /* Instead of using getParameterValues() which will get you String array, in your case no need for that. You need only one `Value`, so you go with `getParameter` */
    System.out.print(request.getParameter(paramName));
}

输出:

0_Firstname - abc

1_Lastname - xyz

etc....

于 2014-11-14T12:03:47.967 回答
0

您不会使用request.getParameterNames();.

您可以使用

String [] parameterNames =  new String[]{"param1","param2","param3"};

for(String param : parameterNames){
 System.out.println(param);
}

其中parameterNames 包含您想要参数的序列。您甚至可以配置它并从配置文件中读取序列。

或者

您可以使用

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

或者

您可以使用

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

得到查询字符串后,可以按照自己的方式拆分使用。

于 2014-11-14T11:09:03.780 回答