2011-03-15 75 views
1

我想在我的JSP上使用下拉菜單,但是......我不知道如何捕獲所選項目的值並將其傳遞給我的Servlet,並有一些QUERY將值添加到我的數據庫。如何從jsp的DropDown菜單捕獲值到Servlet?

你能給我一些想法或線索如何編碼嗎?

PS。我還需要下拉菜單中的項目轉換爲Integer,因爲我將它添加到我的數據庫中存儲的數據。

這對於像我這樣的初學者來說會很難嗎? 我應該使用Textbox並讓用戶手動輸入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> 

而且我想知道如果在該行的<option value="25">25</option>是真正的值我的servlet可以捕獲?

很抱歉,如果我有這麼多的問題... :)

+0

更好的設計是保持在服務器端的選項值和其標籤像'的ServletContextListener '或者某種。檢查[http://stackoverflow.com/questions/8840655/how-get-selected-option-label-from-a-dropdown-list] –

回答

1
int selectedItem; 
if(request.getParameter("Points")!=null) 
{ 
    selectedItem=Integer.ParseInt(request.getParameter("Points")); 
} 
0

一起來你可能想,這樣是傳遞到JSP數據添加一個方法=「後」到你的表單標籤。

至於真實的檢索選定值代碼可能會想看看是這樣的:

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

然後你有,你可以在SQL查詢中使用一個變量藏匿選擇的值。

喜歡的東西:

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

確保你有一個整數,可與方便parseInt函數()函數

JSP來完成關於你的最後一個問題。屬性的值就是將實際被抓是,該選項標籤之間的號碼就是什麼是真正向用戶顯示

-1
int selectedItem; 

if((selectedItem=Integer.ParseInt(request.getParameter("Points"))!=null) 
{ 

     // It woud take Less Time 
     // Do Your Logic 
} 
+0

錯誤的代碼。當參數爲null時拋出'NumberFormatException'。即使如此,它在理論上也會在自動裝箱過程中拋出'NullPointerException',與'!= null'相比,因爲'int'永遠不會是'null'。 – BalusC