In this tutorial, we show you 3 different ways of render HTML checkbox fields:

1. <form:checkbox /> – Single Checkbox

Generate a classic single checkbox, with a boolean value.

public class Customer{
boolean receiveNewsletter; //...}
Checked by default…
If you set the “
receiveNewsletter” boolean value to true, this checkbox will be checked. For example :

 

public class Customer{
boolean receiveNewsletter = true; //...}
 

2. <form:checkbox /> – Multiple Checkboxes

Generate multiple checkboxes and hard-coded the value.

public class Customer{
String [] favLanguages; //...}
Java
C++
.Net
Checked by default…
If you want to make the checkbox with value “Java” is checked by default, you can initialize the “
favLanguages” property with value “Java”. For example :

 

//SimpleFormController...        @Override	protected Object formBackingObject(HttpServletRequest request)		throws Exception {
  Customer cust = new Customer(); cust.setFavLanguages(new String []{
"Java"});  return cust;  }

3. <form:checkboxes /> – Multiple Checkboxes

Generate a runtime list for the checkboxes value, and link it to Spring’s form tag <form:checkboxes>.

//SimpleFormController...	protected Map referenceData(HttpServletRequest request) throws Exception {
  Map referenceData = new HashMap(); List
webFrameworkList = new ArrayList
(); webFrameworkList.add("Spring MVC"); webFrameworkList.add("Struts 1"); webFrameworkList.add("Struts 2"); webFrameworkList.add("Apache Wicket"); referenceData.put("webFrameworkList", webFrameworkList);  return referenceData; }
Checked by default…
If you want to make 2 checkboxes with value “Spring MVC” and “Struts 2″ are checked by default, you can initialize the “
favFramework” property with value “Spring MVC” and “Struts 2″. Fro example :

 

//SimpleFormController...        @Override	protected Object formBackingObject(HttpServletRequest request)		throws Exception {
  Customer cust = new Customer(); cust.setFavFramework(new String []{
"Spring MVC","Struts 2"});  return cust; }
Note

 

For multiple checkboxes, as long as the “path” or “property” value is equal to any of the “checkbox values – ${dynamic-list}“, the matched checkbox will be checked automatically.

Full checkbox example

Let’s go thought a complete Spring MVC checkbox example :

1. Model

A customer model class to store the checkbox value.

File : Customer.java

package com.mkyong.customer.model; public class Customer{
  //checkbox boolean receiveNewsletter = true; //checked it String [] favLanguages; String [] favFramework;  public String[] getFavFramework() {
return favFramework; } public void setFavFramework(String[] favFramework) {
this.favFramework = favFramework; } public boolean isReceiveNewsletter() {
return receiveNewsletter; } public void setReceiveNewsletter(boolean receiveNewsletter) {
this.receiveNewsletter = receiveNewsletter; } public String[] getFavLanguages() {
return favLanguages; } public void setFavLanguages(String[] favLanguages) {
this.favLanguages = favLanguages; }}

2. Controller

A SimpleFormController to handle the form checkbox value.

File : CheckBoxController.java

package com.mkyong.customer.controller; import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.validation.BindException;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.SimpleFormController;import com.mkyong.customer.model.Customer; public class CheckBoxController extends SimpleFormController{
  public CheckBoxController(){
setCommandClass(Customer.class); setCommandName("customerForm"); }  @Override protected Object formBackingObject(HttpServletRequest request) throws Exception {
  Customer cust = new Customer();  //Make "Spring MVC" and "Struts 2" as default checked value cust.setFavFramework(new String []{
"Spring MVC","Struts 2"});  //Make "Java" as default checked value cust.setFavLanguages(new String []{
"Java"});  return cust;  }  @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
  Customer customer = (Customer)command; return new ModelAndView("CustomerSuccess","customer",customer);  }  //Generate the data for web framework multiple checkboxes protected Map referenceData(HttpServletRequest request) throws Exception {
  Map referenceData = new HashMap(); List
webFrameworkList = new ArrayList
(); webFrameworkList.add("Spring MVC"); webFrameworkList.add("Struts 1"); webFrameworkList.add("Struts 2"); webFrameworkList.add("Apache Wicket"); referenceData.put("webFrameworkList", webFrameworkList);  return referenceData;  }}

3. Validator

A simple form validator make sure the “favLanguages” property is not empty.

File : CheckBoxValidator.java

package com.mkyong.customer.validator; import org.springframework.validation.Errors;import org.springframework.validation.Validator;import com.mkyong.customer.model.Customer; public class CheckBoxValidator implements Validator{
  @Override public boolean supports(Class clazz) {
//just validate the Customer instances return Customer.class.isAssignableFrom(clazz); }  @Override public void validate(Object target, Errors errors) {
  Customer cust = (Customer)target;  if(cust.getFavLanguages().length==0){
errors.rejectValue("favLanguages", "required.favLanguages"); } }}

File : message.properties

required.favLanguages = Please select at least a favorite programming language!

4. View

A JSP page to show the use of Spring’s form tag <form:checkbox /> and <form:checkboxes />.

File : CustomerForm.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> 	

Spring's form checkbox example

 
Subscribe to newsletter? :
Favourite Languages :
Java
C++
.Net
Favourite Web Frameworks :
 

Use JSTL to loop over the submitted checkboxes value, and display it.

File : CustomerSuccess.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 	

Spring's form checkbox example

  Receive Newsletter : ${customer.receiveNewsletter}
  Favourite Languages :
[
]
  Favourite Web Frameworks :
[
]

5. Spring Bean Configuration

Link it all ~

 
 
 
 
 
/WEB-INF/pages/
.jsp
 

6. Demo

Access the page – http://localhost:8080/SpringMVCForm/checkbox.htm

SpringMVC-CheckBox-Example-1

If the user did not select any language checkboxes value while submitting the form, display and highlight the error message.

SpringMVC-CheckBox-Example-2

If the form is submitted successfully, just display the submitted checkboxes value.

SpringMVC-CheckBox-Example-3