Spring <form:checkbox> and <form:checkboxes> Tag

In this example, you will learn how to create a HTML checkbox with Spring <form:checkbox> tag. For Example :

<form:checkbox path="favFruit" value="Apple" />Apple 
<form:checkboxes items="${hobbiesList}" path="hobbies" />

You can create a single checkbox using <form:checkbox> tag or a list of checkboxes created at runtime using <form:checkboxes> tag

In order to use the Spring Form Tags you need to include the following taglib directive in the jsp page.

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

First create a new Dynamic Web Project and configure it as Maven Project. For Reference, Click Here

  <properties>
	<spring.version>3.1.0.RELEASE</spring.version>
  </properties>
  <dependencies>

	<!-- Spring 3 dependencies -->
	<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>taglibs</groupId>
		<artifactId>standard</artifactId>
		<version>1.1.2</version>
	</dependency>
	<dependency>
		<groupId>jstl</groupId>
		<artifactId>jstl</artifactId>
		<version>1.1.2</version>
	</dependency>
  </dependencies>

1. Model

Following is the Person class.

package com.kruders.domain;

public class Person {
	boolean newsletterSubscription;
	String hobbies[];
	String favFruit[];
	public boolean isNewsletterSubscription() {
		return newsletterSubscription;
	}
	public void setNewsletterSubscription(boolean newsletterSubscription) {
		this.newsletterSubscription = newsletterSubscription;
	}
	public String[] getHobbies() {
		return hobbies;
	}
	public void setHobbies(String[] hobbies) {
		this.hobbies = hobbies;
	}
	public String[] getFavFruit() {
		return favFruit;
	}
	public void setFavFruit(String[] favFruit) {
		this.favFruit = favFruit;
	}
}

2. Controller

In order to handle spring forms, you need your controller to extend SimpleFormController. Following class shows you how to extend SimpleFormController

PersonController.java

package com.kruders.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.kruders.domain.Person;

public class PersonController extends SimpleFormController{
	public PersonController(){
		setCommandClass(Person.class);
		setCommandName("personForm");
	}
	
	@Override
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
 		Person person = new Person();
 		person.setNewsletterSubscription(true);
 		person.setHobbies(new String []{"Gardening"});
 		return person;
 	}
	
	@Override
	protected ModelAndView onSubmit(Object command) throws Exception {
		Person person = (Person) command;
		return new ModelAndView("personSuccess","person",person);
	}
	
	
	protected Map referenceData(HttpServletRequest request) throws Exception {
 
		Map referenceData = new HashMap();
		List<String> hobbiesList = new ArrayList<String>();
		hobbiesList.add("Gardening");
		hobbiesList.add("Listening Music");
		hobbiesList.add("Writing Technical Tutorials");
		referenceData.put("hobbiesList", hobbiesList);
 
		return referenceData;
 
	}
}

3. Form Validation

To validate the form fields we have a seperate PersonValidator class that implements the Validator interface, override the validate() method perform all the validations.

Following in the PersonValidator class.

package com.kruders.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.kruders.domain.Person;

public class PersonValidator implements Validator{
	@Override
	public boolean supports(Class<?> clazz) {
		return Person.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		Person person = (Person) target;
		if(person.getHobbies().length == 0) {
			errors.rejectValue("hobbies", "hobbies.required");
		}
	}
}

4. Properties File

A properties file to store all the error messages. Here we have the error messages in a seperate properties file so we add the error code, you can even add the error messages directly.

messages.properties

hobbies.required = Select at least one hobby

5. View

Following is the form person form that contains Spring’s Form Tags and display error message if any.

form:errors tag to dispaly errors in jsp files.

personForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring &lt;form:checkboxes&gt; Checkbox</title>
<style>
.error {
	color: red;
}
 
</style>
</head>
<body>
<form:form method="POST" commandName="personForm">
	<table>
		<tr>
			<td>Favourite Fruits :</td>
			<td>
				<form:checkbox path="favFruit" value="Apple" />Apple 
				<form:checkbox path="favFruit" value="Mango" />Mango 
			</td>
			<td><form:errors path="favFruit" cssClass="error" /></td>
		</tr>
		<tr>
			<td>Hobbies :</td>
			<td><form:checkboxes items="${hobbiesList}"
						path="hobbies" /></td>
			<td><form:errors path="hobbies" cssClass="error" /></td>
		</tr>
		<tr>
			<td><form:checkbox path="newsletterSubscription" /></td>
			<td>Subscibe to Newsletter :</td>
			<td><form:errors path="newsletterSubscription" cssClass="error" /></td>
		</tr>
	</table>
	<tr>
			<td colspan="3"><input type="submit" value="Submit"></td>
		</tr>
</form:form>
</body>
</html>

On successful submission of personform, personSuccess.jsp page will be displayed.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Output</title>
</head>
<body>
Favourite Fruits :
<c:forEach items="${person.favFruit}" var="fruit">
		<c:out value="${fruit}" /> <br/>
</c:forEach>
<br />
Hobbies :
<c:forEach items="${person.hobbies}" var="hobby">
		<c:out value="${hobby}" /> <br/>
</c:forEach>
<br />
Receive Newsletter : ${person.newsletterSubscription}
<br />
</body>
</html>

6. Spring Bean Configuration

We now declare the controller and validator for the personform Spring Bean Configuration file.

	<bean class="com.kruders.controller.PersonController">
		<property name="formView" value="personForm" />
		<property name="successView" value="personSuccess" />
	 
		<!-- Map a validator -->
		<property name="validator">
			<bean class="com.kruders.validator.PersonValidator" />
		</property>
 	</bean>

Also add the properties file.

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="messages" />

7. Run

Now when you run the project, following screen will be displayed as in Figure 61.1

Figure 61.1 Figure 61.1


Now when you select any checkbox and click submit button, following screen will be displayed as shown in Figure 61.2

Figure 61.2 Figure 61.2

You can download the source code of this example here.


, ,

No comments yet.

Leave a Reply