Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to receive html check box value in spring mvc controller

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");
  }
}
like image 618
Yasitha Bandara Avatar asked May 21 '16 06:05

Yasitha Bandara


2 Answers

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";
}
like image 125
Phoste Avatar answered Oct 29 '22 09:10

Phoste


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 :)

like image 43
Paolo Avatar answered Oct 29 '22 10:10

Paolo