【问题标题】:how can I capture the value from a DropDown menu at jsp to Servlet?如何从 jsp 的下拉菜单中将值捕获到 Servlet?
【发布时间】:2011-03-15 14:06:05
【问题描述】:

我想在我的 JSP 上使用下拉菜单,但是...我不知道如何捕获所选项目的值并将其传递给我的 Servlet 并有一些查询来将值添加到我的数据库中。

你能给我一些想法或线索如何编码吗?

PS。我还需要将下拉菜单中的项目转换为整数,因为我会将其添加到我的数据库中存储的数据中。

这对于像我这样的初学者来说会很难吗? 我应该使用文本框并让用户手动输入 INTEGER 而不是下拉菜单吗?

提前非常感谢:)

我的 Jsp 菜单是这样的:

<body>
    <form action="AddPoints">
      <table width="408" border="0">
        <tr>
          <td width="402"><h3 align="center">Enter Points:</h3>
            <h3 align="center">
              <label for="Points"></label>
              <select name="Points" size="1" id="Points">
                <option value="5" selected>5</option>
                <option value="10">10</option>
                <option value="15">15</option>
                <option value="20">20</option>
                <option value="25">25</option>
              </select>
              <br/>
            </h3>
            <h3 align="center"><strong></strong>
              <input type="submit" name="AddPoints" id="AddPoints" value="Add Points">
          </h3></td>
        </tr>
      </table>
</form>
</body>

我还想知道这一行的 &lt;option value="25"&gt;25&lt;/option&gt; 是否是我的 servlet 可以捕获的真正值?

对不起,如果我有这么多问题... :)

【问题讨论】:

标签: jsp drop-down-menu web-applications


【解决方案1】:
int selectedItem;
if(request.getParameter("Points")!=null)
{
   selectedItem=Integer.ParseInt(request.getParameter("Points"));
}

【讨论】:

    【解决方案2】:

    首先,您可能希望将 Method='post' 添加到表单标签,以便将数据传递到 jsp。

    至于实际检索所选值,您的代码可能希望看起来像这样:

     var selection = request.getParameter('Points');
    

    然后,您将选定的值存储在一个变量中,您可以在 SQL 查询中使用该变量。

    类似:

    var sQL = "Select * From xxx where Points="+selection
    

    确保你有一个整数可以在 jsp 中使用方便的 parseInt() 函数来完成

    关于你的最后一个问题。 value 属性是实际会被捕获的,是的,选项标签之间的数字正是实际显示给用户的内容

    【讨论】:

      【解决方案3】:
      int selectedItem;
      
      if((selectedItem=Integer.ParseInt(request.getParameter("Points"))!=null)
      {
      
               // It woud take Less Time
               // Do Your Logic
      }
      

      【讨论】:

      • 错误代码。当参数为null 时,这会抛出NumberFormatException。即使那样,理论上它会在自动装箱期间抛出 NullPointerException!= null 相比,因为 int 永远不会是 null
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 2014-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 2022-11-02
      相关资源
      最近更新 更多