【问题标题】:How to get all dropdown values in string array in java?如何在java中获取字符串数组中的所有下拉值?
【发布时间】:2015-01-31 07:14:17
【问题描述】:

我知道这是一个非常基本的问题,但我无法跟踪错误

这是我的下拉列表

<select name="prodnd" id="prodnd" style="display:none">
                                  <option value="Andorra">Andorra</option>
                                        <option value="Antarctica">Antarctica</option>
                                        <option value="Bulgaria">Bulgaria</option>  
                                </select>

我想要 servlet 中的所有这些选项值

我在 servlet 中尝试了 getParameterValues

String[] prodn = request.getParameterValues("prodnd");

但我只能获得第一个选项值....

我想要所有的值

【问题讨论】:

  • 您可能只是选择了第一个元素?
  • 在选择选项时使用Ctrl+click

标签: java html arrays servlets html-select


【解决方案1】:

multiple 属性添加到您的&lt;select&gt; 控件

<select name="prodnd" id="prodnd" multiple size="3">

然后确保使用CTRL + click 选择多个值。


不要使用&lt;select&gt; 控件发送隐藏数据。使用&lt;input type="hidden" ... &gt; 作为
<input type="hidden" name="prodnd" id="prodnd" value="Andorra,Antarctica,Bulgaria" />

然后简单地将值拆分回 Servlet 中的数组

String[] prodnd = request.getParameter("prodnd").split(",");

【讨论】:

  • 其实我想把它隐藏起来,在提交表单时,所有值都应该发送到 servlet .....我正在使用这个下拉框来存储用户不会的值看不到......所以用户不会从下拉列表中选择任何东西......它只是用于在服务器端发送值......
  • 谢谢这成功了......我会添加.split(',') 方法来将我的所有值放入一个数组......
【解决方案2】:

&lt;select&gt; 标记需要选择单个元素(通过 JS 或通过用户交互来查找它将发送的数据。

&lt;input type="hidden"&gt; 可能有效,但是您必须将其转换为数组或结构,因为您将收到它作为字符串。

JSON 或序列化数据也可能是其他选项。

我想知道用例可能是什么。如果您尝试在用户会话中保留数据,那么您的 servlet 中的 Session attribute 可能是一个更好的选择

【讨论】:

    【解决方案3】:

    只需使用隐藏字段:

    <input type='hidden' name='prodnd' value='Andorra'/>
    <input type='hidden' name='prodnd' value='Antarctica'/>
    <input type='hidden' name='prodnd' value='Bulgaria'/>
    

    用户将看不到它,值将被发送到服务器

    如果您仍想使用下拉菜单,请将所有选项标记为选中:

    <select name="prodnd" id="prodnd" style="display:none" multiple>
      <option value="Andorra" selected>Andorra</option>
      <option value="Antarctica" selected>Antarctica</option>
      <option value="Bulgaria" selected>Bulgaria</option>
    </select>
    

    【讨论】:

      【解决方案4】:

      在选择标签中使用多个属性

      <form action="servlet" method="post">
          <select name="prodnd" multiple>
              <option value="Andorra">Andorra</option>
              <option value="Antarctica">Antarctica</option>
              <option value="Bulgaria">Bulgaria</option>
          </select>
          <input type="submit">
      </form>
      

      【讨论】:

      • 因为你没有得到它的要求。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      相关资源
      最近更新 更多