In this post we’ll see how to use checkbox and checkboxes provided by the form tag in the Spring MVC framework.
Technologies used
Following is the list of tools used for the Spring MVC checkbox and checkboxes form tag example.
- Spring 6.1.x Release (Spring core, spring web, spring webmvc).
- Java 21
- JSTL tag library
- Tomcat server V 10.x
Spring MVC Project structure using Maven
Maven Dependencies
Apart from Spring dependencies following dependency is also needed in the pom.xml for JSTL tags.
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
<version>3.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<form:checkbox> and <form:checkboxes> tags in Spring MVC
- <form:checkbox>- This tag renders an HTML 'input' tag with type 'checkbox'. With this tag the value for the checkbox
is hardcoded with in the JSP page.
- <form:checkboxes>- This tag renders multiple HTML 'input' tags with type 'checkbox'. If you don't want to list the
value for the checkbox with in the JSP but want to provide a list of available options at runtime and pass that in to the tag then
you can use checkboxes tag. You pass in an Array, a List or a Map containing the available options in the "items" property.
Spring MVC checkbox example
For the Spring MVC form checkbox example let’s assume there is a class UserPreferences which is used to list out preferences
as check boxes in the JSP page.
Spring MVC checkbox example – Model Class
public class UserPreferences {
private boolean receiveNewsletter;
private String[] cardioExercises;
private String favouriteFood;
public boolean isReceiveNewsletter() {
return receiveNewsletter;
}
public void setReceiveNewsletter(boolean receiveNewsletter) {
this.receiveNewsletter = receiveNewsletter;
}
public String[] getCardioExercises() {
return cardioExercises;
}
public void setCardioExercises(String[] cardioExercises) {
this.cardioExercises = cardioExercises;
}
public String getFavouriteFood() {
return favouriteFood;
}
public void setFavouriteFood(String favouriteFood) {
this.favouriteFood = favouriteFood;
}
}
Spring MVC checkbox example – View
Following JSP (preferences.jsp) shows all the approaches to the checkbox tag in Spring MVC.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<title>Spring MVC checkbox example in form tag</title>
</head>
<body>
<form:form method="POST" action="showPreferences" modelAttribute="preferences">
<table>
<tr>
<td>Subscribe to newsletter?:</td>
<!-- Property is of type java.lang.Boolean-->
<td><form:checkbox path="receiveNewsletter"/></td>
</tr>
<tr>
<td>Favorite cardio exercises:</td>
<!-- Property is of an array or of type java.util.Collection -->
<td>Running: <form:checkbox path="cardioExercises" value="Running"/>
<td>Skipping: <form:checkbox path="cardioExercises" value="Skipping"/>
<td>Cycling: <form:checkbox path="cardioExercises" value="Cycling"/>
<td>Burpee: <form:checkbox path="cardioExercises" value="Burpee"/>
</tr>
<tr>
<td>Favourite Food:</td>
<%-- Property is of type java.lang.Object --%>
<td>Raw Vegetables: <form:checkbox path="favouriteFood" value="Raw Vegetables"/></td>
<td>Steamed Vegetables: <form:checkbox path="favouriteFood" value="Steamed Vegetables"/></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form:form>
</body>
</html>
The check boxes with in the JSP are checked or left unchecked based on the following-
- When the bound value is of type java.lang.Boolean, the input(checkbox) is marked as 'checked' if the bound value is true.
- When the bound value is of type array or java.util.Collection, the input(checkbox) is marked as 'checked' if the configured
value is present in the bound Collection.
- For any other bound value type, the input(checkbox) is marked as 'checked' if the configured setValue(Object) is equal
to the bound value.
The values for the properties are taken from an object of type UserPreferences bean which is bound using the attribute
“modelAttribute” with in the form tag. The object is set with in the handler method of the Controller class.
There is another JSP that is used to display the values selected by checking the check boxes.
showPreferences.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<title>User Preferences</title>
</head>
<body>
<div>
<span>Subscribe to newsletter?:</span>
<span>${preferences.receiveNewsletter}</span>
</div>
<div>
<span>Favorite cardio exercises:</span>
<c:forEach items="${preferences.cardioExercises}" var="exercise" varStatus="counter">
<span>${exercise}
<c:if test="${not counter.last}">
<c:out value="," ></c:out>
</c:if>
</span>
</c:forEach>
</div>
<div>
<span>Favourite Food:</span>
<span>${preferences.favouriteFood}</span>
</div>
</table>
</body>
</html>
Spring MVC checkbox example – Configuration changes
Since JSTL tags are also used so you need to configure InternalResourceViewResolver to resolve a JstlView for that
following configuration has to be added in the configuration file.
<bean id="JSPViewResolver" class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
Spring MVC checkbox example – Controller class
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.netjstech.springweb.model.UserPreferences;
@Controller
public class PreferenceController {
@GetMapping("/preferences")
public String showUserPreferences(Model model) throws Exception{
UserPreferences pref = new UserPreferences();
pref.setReceiveNewsletter(true);
pref.setCardioExercises(new String[]{"Running", "Burpee"});
pref.setFavouriteFood("Steamed Vegetables");
model.addAttribute("preferences", pref);
return "preferences";
}
@RequestMapping(value = "/showPreferences", method = RequestMethod.POST)
public String showPreferences(@ModelAttribute("preferences") UserPreferences preferences, Model model) throws Exception{
//System.out.println("In ShowPreferences");
model.addAttribute("preferences", preferences);
return "showPreferences";
}
}
In the Controller class, showUserPreferences() method is used to handle the /preferences request path. Method returns the view name as "preferences" which resolves to /WEB-INF/jsp/preferences.jsp JSP.
In the handler method, object of UserPreferences class is set to the Model which is used in the JSP to mark the check box as
checked or leave it unchecked. If you want some of the check boxes to be checked in the JSP by default then you can set the values for the properties in the UserPreferences object.
Another handler method showPreferences() handles the request when submit button is clicked in the preferences.jsp.
Deploying and testing the application
Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/springwebproj/preferences (This is as per my project name- springwebproj)
In the above page it shows those check boxes as checked for which values are set in the handler method of the controller class.
In the following page some more boxes are checked before clicking on submit button.
Page which shows all the values that are checked.
Spring MVC checkboxes tag example
If you want to provide the list of options for the checkbox at runtime rather than hardcoding them then you can add checkboxes
tag in Spring MVC application. You pass in an Array, a List or a Map containing the available options in the "items" property.
Spring MVC checkboxes example – Model Class
public class UserPreferences {
private boolean receiveNewsletter;
private String[] cardioExercises;
private List<String> favouriteFood;
public boolean isReceiveNewsletter() {
return receiveNewsletter;
}
public void setReceiveNewsletter(boolean receiveNewsletter) {
this.receiveNewsletter = receiveNewsletter;
}
public String[] getCardioExercises() {
return cardioExercises;
}
public void setCardioExercises(String[] cardioExercises) {
this.cardioExercises = cardioExercises;
}
public List<String> getFavouriteFood() {
return favouriteFood;
}
public void setFavouriteFood(List<String> favouriteFood) {
this.favouriteFood = favouriteFood;
}
}
Spring MVC checkboxes example – Views
preferences.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<title>Spring MVC checkbox example in form tag</title>
</head>
<body>
<form:form method="POST" action="showPreferences" modelAttribute="preferences">
<table>
<tr>
<td>Subscribe to newsletter?:</td>
<!-- Property is of type java.lang.Boolean-->
<td><form:checkbox path="receiveNewsletter"/></td>
</tr>
<tr>
<td>Favorite cardio exercises:</td>
<td><form:checkboxes path="cardioExercises" items="${prefMap}"/></td>
</tr>
<tr>
<td>Favourite Food:</td>
<td><form:checkboxes path="favouriteFood" items="${foodList}"/></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form:form>
</body>
</html>
As you can see now <form:checkboxes> tag is used with the items property. The values used with the items property in the JSP prefMap and foodList should be available as a model attribute containing String of values to be selected from. If a Map is used, the map entry key will be used as the value and the map entry’s value will be used as the label to be displayed.
There is another JSP that is used to display the values selected by checking the check boxes.
showPreferences.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<title>User Preferences</title>
</head>
<body>
<div>
<span>Subscribe to newsletter?:</span>
<span>${preferences.receiveNewsletter}</span>
</div>
<div>
<span>Favorite cardio exercises:</span>
<c:forEach items="${preferences.cardioExercises}" var="exercise" varStatus="counter">
<span>${exercise}
<c:if test="${not counter.last}">
<c:out value="," ></c:out>
</c:if>
</span>
</c:forEach>
</div>
<div>
<span>Favourite Food:</span>
<c:forEach items="${preferences.favouriteFood}" var="food" varStatus="foodCounter">
<span>${food}
<c:if test="${not foodCounter.last}">
<c:out value="," ></c:out>
</c:if>
</span>
</c:forEach>
</div>
</body>
</html>
Spring MVC checkboxes example – Controller class
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.netjstech.springweb.model.UserPreferences;
@Controller
public class PreferenceController {
@GetMapping("/preferences")
public String showUserPreferences(Model model) throws Exception{
UserPreferences pref = new UserPreferences();
//default check values
pref.setReceiveNewsletter(true);
pref.setCardioExercises(new String[]{"Running", "Burpee"});
pref.setFavouriteFood(Arrays.asList("Boiled legumes", "Steamed Vegetables"));
// Preparing values for "Favorite cardio exercises" check box
Map<String, String> prefMap = new HashMap<>();
prefMap.put("Running", "Running");
prefMap.put("Burpee", "Burpee");
prefMap.put("Skipping", "Skipping");
prefMap.put("Cycling", "Cycling");
model.addAttribute("prefMap", prefMap);
model.addAttribute("preferences", pref);
return "preferences";
}
// List for "Favourite Food" check box
@ModelAttribute("foodList")
public List<String> getFoodList(){
List<String> foodList = new ArrayList<>();
foodList.add("Steamed Vegetables");
foodList.add("Boiled legumes");
foodList.add("Pizza");
foodList.add("Burger");
return foodList;
}
@RequestMapping(value = "/showPreferences", method = RequestMethod.POST)
public String showPreferences(@ModelAttribute("preferences") UserPreferences preferences, Model model) throws Exception{
model.addAttribute("preferences", preferences);
return "showPreferences";
}
}
As you can see prefMap and foodList which are used in the JSP to show options for checkboxes in the JSP are set here as model
attribute. If you want some of the check boxes to be checked in the JSP then you can set the values for the properties in
the UserPreferences object.
Deploying and testing the application
Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/springwebproj/preferences
This is the page with the check boxes marked as checked for the properties set in the handler method of the controller class.
Page which shows all the values that are checked.
Reference-
https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib
That's all for this topic Spring MVC Checkbox And Checkboxes Form Tag Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
-
Spring Web MVC Tutorial
- Spring MVC Radiobutton And Radiobuttons Form Tag Example
-
Spring MVC PDF Generation Example
-
Spring MVC Generate Response as JSON Example
-
Spring MVC Form Example With Bean Validation
You may also like-
-
Connection Pooling With Apache DBCP Spring Example
-
BeanFactoryAware Interface in Spring Framework
-
Autodiscovery of Bean Using componenent-scan in Spring
-
How to Inject Prototype Scoped Bean in Singleton Bean
-
Volatile in Java
-
Type Erasure in Java Generics
-
Searching Within a String Using indexOf(), lastIndexOf() And contains() Methods
-
How to Sort an ArrayList in Descending Order in Java