Spring MVC checkbox data process
This demo will show you how to process check box data and pass its value to the controller. To pass selected check box data to the controller create list attribute in your model class use same attribute on your jsp page:
Model class attribute:
List<String> selectedCheckBox;
Jsp page:
<c:forEach items="${person.personsList}" var="elements" varStatus="loop"> <tr> <td ><form:checkbox path="selectedCheckBox" class="person_data" value="${elements.name}"/></td> <td><c:out value='${elements.name}' /></td> <td><c:out value='${elements.department}' /></td> <td><c:out value='${elements.location}' /></td> <td><c:out value='${elements.zip}' /></td> <td id=salary<c:out value="${loop.index}"/>><fmt:formatNumber value="${elements.salary}" type="currency"/></td> </tr> </c:forEach>
Please have detail working example below:
Below are needed:
- Eclipse 3.2 or above (Download from here) – Note for this demo we have used eclipse Kepler
- JDK 1.6 or above (Download from here )
- Tomcat 6 or above (Please follow link to install and configure tomcat in eclipse: Configure and Run Tomcat server in eclipse )
- Spring version 4.0.3.RELEASE (Dependency already included in pom.xml)
- Maven 3.0.4
- JQuery js file (Links are already include in jsp page you don’t need to download anything)
After all set up and configuration you will see below screen:
- Create maven project name SpringMultiCheckbox in eclipse (Please use this link if you are not familiar how to create maven project in eclipse: Create maven Project Eclipse)
- Below shows project structure:
- Please add below dependency in pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javahonk</groupId> <artifactId>SpringMultiCheckbox</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringMultiCheckbox Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>4.0.3.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>runtime</scope> </dependency> </dependencies> <build> <finalName>SpringMultiCheckbox</finalName> </build> </project>
- Please copy below XML into your web.xml file
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.web</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <welcome-file-list> <welcome-file>helloWorld.web</welcome-file> </welcome-file-list> </web-app>
- Now create file name: dispatcher-servlet.xml inside WEB-INF folder and copy and paste below content
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.javahonk.controller" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
- Create jsp folder inside WEB-INF folder
- Create jsp file name: helloWorld.jsp and copy paste below code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Spring 3 MVC</title> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script type="text/javascript"> function goBackToHomePage() { window.location = "/SpringMultiCheckbox/helloWorld.web"; } function selectAllCheckBox() { if (document.getElementById('select_all').checked == true) { $('.person_data').each(function() { this.checked = true; }); } else { $('.person_data').each(function() { this.checked = false; }); } } </script> </head> <body> <form:form id="multiCheckBox" commandName="person" method="post" action="multiCheckbox.web"> <h2>Multiple check box: ${message}</h2> <table cellspacing="0" cellpadding="0" border="1" width="718"> <tr> <Td><h2>${selected}</h2></Td> </tr> <tr> <td><div style="height:300px; overflow:auto;"><table cellspacing="0" cellpadding="0" border="0" width="100%"> <tr> <td><input type="checkbox" name="Select All" id="select_all" onclick="selectAllCheckBox();"/></td> <td><h3>Name</h3></td> <td><h3>Department</h3></td> <td><h3>Location</h3></td> <td><h3>Zip</h3></td> <td><h3>Salary</h3></td> </tr> <c:forEach items="${person.personsList}" var="elements" varStatus="loop"> <tr> <td ><form:checkbox path="selectedCheckBox" class="person_data" value="${elements.name}"/></td> <td><c:out value='${elements.name}' /></td> <td><c:out value='${elements.department}' /></td> <td><c:out value='${elements.location}' /></td> <td><c:out value='${elements.zip}' /></td> <td id=salary<c:out value="${loop.index}"/>><fmt:formatNumber value="${elements.salary}" type="currency"/></td> </tr> </c:forEach> </table></div></td> </tr> </table><br> <input type="submit" value="Submit Data"> <input type="button" value="Go back to home page" onclick="goBackToHomePage();"> </form:form> </body> </html>
- Create package name com.javahonk.controller inside src/main/java folder
- Create class name: SpringMVCController.java inside com.javahonk.controller pakcage and copy paste below content in it:
package com.javahonk.controller; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class SpringMVCController { @RequestMapping(value="/helloWorld.web", method = RequestMethod.GET) public String printWelcome(ModelMap model, HttpServletRequest request) { model.addAttribute("message", "How to pass data"); model.addAttribute("selected", "Select single, " + "multiple or all check box"); List<Person> personsList = new ArrayList<Person>(); Person person2 = new Person(); for (int i = 0; i <10; i++) { Person person = new Person(); person.setDepartment("IT"); person.setLocation("NY"); person.setName("Java Honk"+i); person.setSalary("100"); person.setZip("00038"); personsList.add(person); } person2.setPersonsList(personsList); model.addAttribute("person",person2); request.getSession().setAttribute("personsList", personsList); return "helloWorld"; } @RequestMapping(value="/multiCheckbox.web", method = RequestMethod.POST) public String multiCheckbox(Person person3, ModelMap model,HttpServletRequest request) { model.addAttribute("message", "How to pass data"); model.addAttribute("selected", "Selected check box data"); List<Person> personList = (List<Person>) request.getSession().getAttribute("personsList"); Person person2 = new Person(); List<Person> selectedPersonList = new ArrayList<Person>(); if (null != personList && personList.size() != 0) { for (Person person : personList) { List<String> selectedPerson = person3 .getSelectedCheckBox(); if (null != selectedPerson && selectedPerson .size()!=0) { for (String string : selectedPerson) { if (string.equalsIgnoreCase( person.getName())) { selectedPersonList.add(person); } } } } } person2.setPersonsList(selectedPersonList); model.addAttribute("person",person2); return "helloWorld"; } }
- Create class name: Person.java inside com.javahonk.controller pakcage and copy paste below content in it:
package com.javahonk.controller; import java.util.List; public class Person { private String name; private String department; private String location; private String zip; private String salary; List<String> selectedCheckBox; List<Person> personsList; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } public List<String> getSelectedCheckBox() { return selectedCheckBox; } public void setSelectedCheckBox(List<String> selectedCheckBox) { this.selectedCheckBox = selectedCheckBox; } public List<Person> getPersonsList() { return personsList; } public void setPersonsList(List<Person> personsList) { this.personsList = personsList; } }
- Now lets run this set up in tomcat server. If you haven’t done tomcat set up in eclipse yet please use this link: Configure and Run Tomcat server in eclipse. Now right click project –>Run As –> Run on server you will see below first screen with sample data:
- Select single, multiple or check box for test. We have selected check box as below and clicked submit data button:
- Below is selected page with data:
Note: If you want pass selected check box index position then use loop.index as below:
<c:forEach items="${person.personsList}" var="elements" varStatus="loop"> <tr> <td ><form:checkbox path="selectedCheckBox" class="person_data" value="${loop.index}"/></td> </tr> </c:forEach>
Download Project: SpringMultiCheckbox
That’s it Spring MVC checkbox data process
hai, thx for the tutorial, but i think there is something wrong in ur code, in your JSP, you using “loop.index” for the checkbox value, and in the controller class, u using “person.getName()” when u want to compare the selected checkbox. it doesn’t match and the return is not as expected
so your example project doesn’t work properly as u describe, need some minor fix. a little bit misleading to a newbie like me 🙂
Thanks. If you see note all the way to the bottom where it’s mentioned that loop.index is just optional field I have added to get index position and its nothing to do with checkbox normal processing.
Hi, i am trying to use our code in eclipse but i am facing error at class=”person_data”. for this tag it is saying Undefined attribute name “class”.
And when i am running my this project then getting error “org.apache.jasper.JasperException: /WEB-INF/jsp/hello.jsp(56,24) Attribute class invalid for tag checkbox according to TLD
” . Please suggest what to do
Please include all jars file in your class path. Please let me know if you are using maven or dynamic web project?
I have included all the spring jar and jstl jar file. There is no compilation error. Spring is working file the only problem is with the tag
instead of this when am using then project is runing fine but when i am clicking on check box then value is getting lost at java means it is not passing the value. please suggest what to do.
Throgh eclipse am using Dynamic web project.
Thanks you so much 🙂
I’m looking for this