Spring Dropdown using <form:select> and <form:option> Tag

The <form:option> tag renders a set of HTML <option> elements, representing possible choices for a <form:select> element. This tag can be used multiple times within a single <html:select> element, either in conjunction with or instead of one or more <html:option> or <html:options> elements. For Example :

<form:option value="Apple" label="Apple" />
<form:options items="${hobbiesList}"/>
<form:select path="hobbies" items="${hobbiesList}" multiple="true" />

1. You can create a single option using <form:option> tag
2. You can create a list of option created at runtime using <form:options> tag
3. You can create a list box using multiple=”true”

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 {
	String hobbies;
	String fruit;
	public String getHobbies() {
		return hobbies;
	}
	public void setHobbies(String hobbies) {
		this.hobbies = hobbies;
	}
	public String getFruit() {
		return fruit;
	}
	public void setFruit(String fruit) {
		this.fruit = fruit;
	}
}

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.setHobbies("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;
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,"hobbies", "hobbies.required");
		if(person.getFruit().equals("Select")){
			errors.rejectValue("fruit", "fruit.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
fruit.required = Select at least one fruit

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>Fruits :</td>
			<td>
				<form:select path="fruit">
				  <form:option value="Select" label="Select" />
				  <form:option value="Apple" label="Apple" />
				  <form:option value="Mango" label="Mango" />
			    </form:select>
			</td>
			<td><form:errors path="fruit" cssClass="error" /></td>
		</tr>
		<tr>
			<td>Hobbies :</td>
			<td><form:select path="hobbies" multiple="true">
					<form:options items="${hobbiesList}"/>
				</form:select>
			</td>
			<td><form:errors path="hobbies" 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>
Fruits :
<c:forEach items="${person.fruit}" var="fruit">
		<c:out value="${fruit}" /> <br/>
</c:forEach>
<br />
Hobbies :<br />
<c:forEach items="${person.hobbies}" var="hobby">
		<c:out value="${hobby}" /> <br/>
</c:forEach>
<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 64.1

Figure 64.1 Figure 64.1


Now when you select some text in dropdown and click submit button, following screen will be displayed as shown in Figure 64.2

Figure 64.2 Figure 64.2

You can download the source code of this example here.

, ,

One Response to Spring Dropdown using <form:select> and <form:option> Tag