问题是如果没有选中复选框,请求无法在springMVC控制器中找到正确的映射函数。因为它似乎只在检查时才发送真值,但如果未检查则不发送false值
<form action="editCustomer" method="post">
<input type="checkbox" name="checkboxName"/>
</form>
&#13;
@RequestMapping(value = "/editCustomer" , method = RequestMethod. POST)
public void editCustomer(@RequestParam("checkboxName")String[] checkboxValue)
{
if(checkboxValue[0])
{
System.out.println("checkbox is checked");
}
else
{
System.out.println("checkbox is not checked");
}
}
&#13;
答案 0 :(得分:8)
我在required = false
中解决了指定@RequestMapping
的类似问题。
这样,如果未在表单中选中复选框,则参数checkboxValue
将设置为null
,如果选中则选中"on"
。
@RequestMapping(value = "/editCustomer" , method = RequestMethod. POST)
public void editCustomer(@RequestParam(value = "checkboxName", required = false) String checkboxValue)
{
if(checkboxValue != null)
{
System.out.println("checkbox is checked");
}
else
{
System.out.println("checkbox is not checked");
}
}
希望这可以帮助某人:)
答案 1 :(得分:3)
我遇到了同样的问题,我终于找到了一个简单的解决方案。
只需将默认值添加到false即可完美运行。
Html代码:
<form action="path" method="post">
<input type="checkbox" name="checkbox"/>
</form>
Java代码:
@RequestMapping(
path = "/path",
method = RequestMethod.POST
)
public String addDevice(@RequestParam(defaultValue = "false") boolean checkbox) {
if (checkbox) {
// do something if checkbox is checked
}
return "view";
}
答案 2 :(得分:2)
我必须使用相同的复选框名称添加隐藏的输入。值必须&#34;检查&#34;然后我可以检查控制器或我的服务类中的字符串数组的长度。
<form action="editCustomer" method="post">
<input type="hidden" name="checkboxName" value="checked">
<input type="checkbox" name="checkboxName"/>
</form>
&#13;
@RequestMapping(value = "/editCustomer" , method = RequestMethod. POST)
public void editCustomer(@RequestParam("checkboxName")String[] checkboxValue)
{
if(checkboxValue.length==2)
{
System.out.println("checkbox is checked");
}
else
{
System.out.println("checkbox is not checked");
}
}
&#13;