如何在 spring mvc 控制器中接收 html 复选框值

新手上路,请多包涵

问题是如果未选中复选框,则请求无法在 springMVC 控制器中找到正确的映射函数。因为它似乎只在选中时才发送 true 值,但如果未选中则不会发送 false 值。

 <form action="editCustomer" method="post">
  <input type="checkbox" name="checkboxName"/>
</form>
 @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");
  }
}

原文由 Yasitha Bandara 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 371
2 个回答

我解决了一个类似的问题,在 required = false @RequestMapping 。通过这种方式,参数 checkboxValue 将被设置为 null 如果未在表单中选中复选框或设置为 "on" if checked.

 @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");
  }
}

希望这可以帮助某人:)

原文由 Paolo 发布,翻译遵循 CC BY-SA 4.0 许可协议

我有同样的问题,我终于找到了一个简单的解决方案。

只需将默认值添加到 false 即可完美运行。

网页代码:

 <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";
}

原文由 Phoste 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏