The problem is if the check box is not checked request can not find the correct mapping function in springMVC controller.Because it seems like it only send true values if it is checked,but it does not send false value if it not checked.
<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");
}
}
I had the same problem and I finally found a simple solution.
Just add a default value to false and it will work out perfectly.
Html code :
<form action="path" method="post">
<input type="checkbox" name="checkbox"/>
</form>
Java code :
@RequestMapping(
path = "/path",
method = RequestMethod.POST
)
public String addDevice(@RequestParam(defaultValue = "false") boolean checkbox) {
if (checkbox) {
// do something if checkbox is checked
}
return "view";
}
I solved a similar problem specifying required = false
in @RequestMapping
.
In this way the parameter checkboxValue
will be set to null
if the checkbox is not checked in the form or to "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");
}
}
Hope this could help somebody :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With