[英]How to post multiple <input type=“checkbox” /> as array to Java servlet?
This question is the same as How to post multiple <input type="checkbox" /> as array in PHP? 此问题与如何在PHP中将多个<input type =“ checkbox” />作为数组发布吗? , but I can't make the solution work in my java servlet setup.
,但是我无法在Java servlet设置中使用该解决方案。 When using the apporach of adding a [] to the name property of the grouped checkboxes, I only get the first checked option.
当使用在分组复选框的name属性中添加[]的方法时,我只会得到第一个选中的选项。 I am not sure if it is the actual posted array that is containing only one element, or if I'm not accessing it right server side.
我不确定是不是仅包含一个元素的实际发布数组,还是我没有在服务器端访问它。 Here is what I do to check the value in java:
这是检查Java中值的方法:
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
for(String name : request.getParameterMap().keySet()){
System.out.println(name +": " + request.getParameter(name));
}
}
this prints countries[]: US
, even if I have more checboxes checked after the US-input. 即使我在输入美国之后选中了更多的复选框,这也会打印country
countries[]: US
。 the value changes after which checkbox is the first of the checked ones. 值会更改,此复选框之后是选中的第一个复选框。 What am I doing wrong?
我究竟做错了什么?
Here is my HTML: 这是我的HTML:
<form action="mypage" method="post">
<input id="cb-country-gb" type="checkbox" name="countries[]" class="hide" value="GB"/>
<input id="cb-country-us" type="checkbox" name="countries[]" class="hide" value="US"/>
<input id="cb-country-ge" type="checkbox" name="countries[]" class="hide" value="GE"/>
<input id="cb-country-es" type="checkbox" name="countries[]" class="hide" value="ES"/>
<button type="submit" class="btn btn-primary">Search</button>
</form>
If you check multiple checkboxes the request contains multiple parameters with name countries[]
. 如果您选中多个复选框,则请求包含名称为
countries[]
多个参数。
If you call request.getParameter("countries[]")
only the first parameter value is returned. 如果调用
request.getParameter("countries[]")
仅返回第一个参数值。
Instead you need to use 相反,您需要使用
String[] checked = request.getParameterValues("countries[]");
if (checked != null)
...
You should use [getParameterValues][1]
that returns an array of String objects containing all of the values the given request parameter has : 您应该使用
[getParameterValues][1]
返回一个String对象数组,其中包含给定请求参数具有的所有值:
Test that with following code: 使用以下代码进行测试:
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
for(String name : request.getParameterMap().keySet()){
for(String value : request.getParameterValues(name)){
System.out.println(name +": " + value);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.