[英]How do I handle a posted String array in 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中的復選框值數組?
從Servlet API文檔中:
的getParameter
public java.lang.String getParameter(java.lang.String name)以字符串形式返回請求參數的值,如果該參數不存在,則返回null。 請求參數是與請求一起發送的額外信息。 對於HTTP Servlet,參數包含在查詢字符串或發布的表單數據中。 僅在確定參數只有一個值時才應使用此方法。 如果參數可能具有多個值,請使用getParameterValues(java.lang.String)。
如果將此方法與多值參數一起使用,則返回的值等於getParameterValues返回的數組中的第一個值。
如果參數數據是在請求正文中發送的(例如在HTTP POST請求中發生),則直接通過getInputStream()或getReader()讀取正文會干擾此方法的執行。
參數:name-指定參數名稱的String返回:表示參數的單個值的String另請參見:getParameterValues(java.lang.String)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.