在我的表单中,用户可以在将表单发布到 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
}
});
我通常会使用以下方式访问文本输入值:
字符串输入 = request.getParameter("input");
发布后如何访问 servlet 中的复选框值数组?
最佳答案
来自 Servlet API 文档:
getParameter
public java.lang.String getParameter(java.lang.String name) Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data. You should only use this method when you are sure the parameter has only one value. If the parameter might have more than one value, use getParameterValues(java.lang.String).
If you use this method with a multivalued parameter, the value returned is equal to the first value in the array returned by getParameterValues.
If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly via getInputStream() or getReader() can interfere with the execution of this method.
Parameters: name - a String specifying the name of the parameter Returns: a String representing the single value of the parameter See Also: getParameterValues(java.lang.String)
关于java - 如何在 servlet 中处理发布的字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26450316/