【问题标题】:How to get values of getParameterValues in the order they are sent?如何按发送顺序获取 getParameterValues 的值?
【发布时间】:2014-11-13 10:41:11
【问题描述】:

我通过 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...我写只是为了表明我想要这个顺序的值。

【问题讨论】:

  • 参数是动态的还是固定的?
  • 看看这个link

标签: java servlets http-post getparameter


【解决方案1】:

试试这个

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

Enumeration 转换为List 以便对它们进行排序。

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....

【讨论】:

  • 当我写 String[] parameterNames = request.getParameterNames();它将 parameterNames 的错误更改类型提供给 Enumeration
  • @bhargavthanki 用Enumeration查看我的更新答案
【解决方案2】:

使用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.

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

【讨论】:

  • 在您的解决方案的第一种方法中,我如何获取参数的值。我可以按顺序获取参数。
  • @bhargav 谢谢对不起,我写错了System.out.println。我的意思是request.getParameter(param)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 2020-03-06
  • 2018-12-24
  • 1970-01-01
  • 2021-02-05
  • 2021-12-05
相关资源
最近更新 更多