Yasitha Bandara Yasitha Bandara - 1 year ago 62
HTML Question

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




Answer Source

I had to add hidden input with same name of the checkbox. Value must be "checked".Then I can check the length of the string array within controller or in my service class.

<form action="editCustomer" method="post">
  <input type="hidden" name="checkboxName" value="checked">
  <input type="checkbox" name="checkboxName"/>
</form>

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download