2014-10-19 49 views
0

在我的表單中,用戶可以在發帖的形式給Servlet之前檢查幾個複選框:如何在servlet中處理髮布的字符串數組?

<input type="checkbox" class="genre" name="genre[]" value="1"><label for="1">First Person Shooter</label><br> 
    <input type="checkbox" class="genre" name="genre[]" value="2"><label for="2">Sports</label><br> 
    <input type="checkbox" class="genre" name="genre[]" value="3"><label for="3">Action/Adventure</label><br> 
    <input type="checkbox" class="genre" name="genre[]" value="4"><label for="4">Educational</label><br> 
    <input type="checkbox" class="genre" name="genre[]" value="5"><label for="5">Puzzle</label><br> 
    <input type="checkbox" class="genre" name="genre[]" value="6"><label for="6">Real Time Strategy</label><br> 
    <input type="checkbox" class="genre" name="genre[]" value="7"><label for="7">Beat em ups</label><br> 
    <input type="checkbox" class="genre" name="genre[]" value="8"><label for="8">Survival Horror</label><br> 

我表單數據發佈到使用AJAX調用和序列化這樣的表單數據的servlet:

$(".mainSurvey").submit(function(e){ 

    e.preventDefault(); //STOP default action 
    var postData = $(".mainSurvey").serializeArray(); 
    var botCatcher = $("#botCatcher").val(); 

    if($(".mainSurvey input:checkbox:checked").length > 0 && botCatcher.length == 0){ 

     $.ajax(
     { 
      type: "POST", 
      url : "DatabaseService", 
      data : postData, 
      success: function(data) 
      { 
       // continue 
      }, 
      error: function(jqXHR, textStatus, errorThrown) 
      { 
       // handle error 
      }); 

     }else{ 
      // handle error 
     } 
}); 

在哪裏我通常會訪問使用文本輸入值:

String input = request.getParameter("input");

如何在發佈後訪問servlet中複選框值的數組?

回答

1

從Servlet API的文檔:

的getParameter

公共java.lang.String中的getParameter(java.lang.String中name)返回一個請求參數的 值作爲一個字符串,或空如果參數 不存在。請求參數是與 請求一起發送的額外信息。對於HTTP Servlet,參數包含在查詢 字符串或發佈的表單數據中。 只有當您確定參數只有一個值時,您才應該使用此方法。如果參數可能有多個值,請使用getParameterValues(java.lang.String)。

如果使用此方法與多值參數,則返回值爲 等於由 getParameterValues返回的數組中的第一個值。

如果參數數據在請求體中發送,例如具有HTTP POST請求發生 ,然後直接通過 的getInputStream()或getReader讀取體()可以與 該方法中,執行干擾。

參數:名稱 - 一個String指定參數 名返回:表示參數的單個值的String參見 另外:getParameterValues(java.lang.String中)

相關問題