Main Tutorials

Spring MVC dropdown box example

In Spring MVC, form tags – <form:select />, <form:option /> or <form:options />, are used to render HTML dropdown box. See following examples :


//SimpleFormController
protected Map referenceData(HttpServletRequest request) throws Exception {
	Map referenceData = new HashMap();
	Map<String,String> country = new LinkedHashMap<String,String>();
	country.put("US", "United Stated");
	country.put("CHINA", "China");
	country.put("SG", "Singapore");
	country.put("MY", "Malaysia");
	referenceData.put("countryList", country);
}

1. <form:select />

Generate a dropbox box with ${countryList}.


<form:select path="country" items="${countryList}" />

HTML code


<select id="country" name="country">
   <option value="US">United Stated</option>
   <option value="CHINA">China</option>
   <option value="SG">Singapore</option>
   <option value="MY">Malaysia</option>
</select> 

2. <form:options />

The <form:options /> have to enclosed with the select tag.


<form:select path="country">
    <form:options items="${countryList}" />
</form:select>

HTML code


<select id="country" name="country">
   <option value="US">United Stated</option>
   <option value="CHINA">China</option>
   <option value="SG">Singapore</option>
   <option value="MY">Malaysia</option>
</select> 

3. <form:option />

The <form:option /> have to enclosed with the select tag as well, and render a single select option, see the following combination.


<form:select path="country">
   <form:option value="NONE" label="--- Select ---"/>
   <form:options items="${countryList}" />
</form:select>

HTML code


<select id="country" name="country">
   <option value="NONE">--- Select ---</option> 
   <option value="US">United Stated</option>
   <option value="CHINA">China</option>
   <option value="SG">Singapore</option>
   <option value="MY">Malaysia</option>
</select> 

4. List box

To render a list box, just add the “multiple=true” attribute in the select tag.


<form:select path="country" items="${countryList}" multiple="true" />

HTML code, with a hidden value to handle the country selections.


<select id="country" name="country" multiple="multiple"> 
    <option value="US">United Stated</option>
    <option value="CHINA">China</option>
    <option value="SG">Singapore</option>
    <option value="MY">Malaysia</option> 
</select>
<input type="hidden" name="_country" value="1"/> 
Select a dropdown box value
For dropdown box, list box or “select” options, as long as the “path” or “property” is equal to the “select option key value“, the options will be selected automatically.

Full dropdown box example

Let’s go thought a complete Spring MVC dropdown box example :

1. Model

A customer model class to store the dropdown box value.

File : Customer.java


package com.mkyong.customer.model;

public class Customer{

	String country;
	String javaSkills;
	
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
	public String getJavaSkills() {
		return javaSkills;
	}
	public void setJavaSkills(String javaSkills) {
		this.javaSkills = javaSkills;
	}	
}

2. Controller

A SimpleFormController to handle the form dropdown box value. Make the java skills’s “Spring” as the default dropdown box selected value.

File : DropDownBoxController.java


package com.mkyong.customer.controller;

import java.util.HashMap;
import java.util.LinkedHashMap;
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 DropDownBoxController extends SimpleFormController{
	
	public DropDownBoxController(){
		setCommandClass(Customer.class);
		setCommandName("customerForm");
	}
	
	@Override
	protected Object formBackingObject(HttpServletRequest request)
		throws Exception {
		
		Customer cust = new Customer();
		
		//make "Spring" as the default java skills selection
		cust.setJavaSkills("Spring");
		
		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);
	
	}
	
	protected Map referenceData(HttpServletRequest request) throws Exception {
		
		Map referenceData = new HashMap();
		
		Map<String,String> country = new LinkedHashMap<String,String>();
		country.put("US", "United Stated");
		country.put("CHINA", "China");
		country.put("SG", "Singapore");
		country.put("MY", "Malaysia");
		referenceData.put("countryList", country);
		
		Map<String,String> javaSkill = new LinkedHashMap<String,String>();
		javaSkill.put("Hibernate", "Hibernate");
		javaSkill.put("Spring", "Spring");
		javaSkill.put("Apache Wicket", "Apache Wicket");
		javaSkill.put("Struts", "Struts");
		referenceData.put("javaSkillsList", javaSkill);
		
		return referenceData;
	}
}

3. Validator

A simple form validator to make sure the “country” and “javaSkills” dropdown box is selected.

File : DropDownBoxValidator.java


package com.mkyong.customer.validator;

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

import com.mkyong.customer.model.Customer;

public class DropDownBoxValidator 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;
	
	   ValidationUtils.rejectIfEmptyOrWhitespace(errors, "javaSkills", "required.javaSkills");
		
	   if("NONE".equals(cust.getCountry())){
		errors.rejectValue("country", "required.country");
	   }
	}
}

File : message.properties


required.country = Please select a country!
required.javaSkills = Please select a java Skill!	

4. View

A JSP page to show the use of Spring’s form tag <form:select />, <form:option /> and <form:options />.

File : CustomerForm.jsp


<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<style>
.error {
	color: #ff0000;
}

.errorblock {
	color: #000;
	background-color: #ffEEEE;
	border: 3px solid #ff0000;
	padding: 8px;
	margin: 16px;
}
</style>
</head>

<body>
	<h2>Spring's form select, option, options example</h2>

	<form:form method="POST" commandName="customerForm">
		<form:errors path="*" cssClass="errorblock" element="div" />
		<table>

			<tr>
				<td>Country :</td>
				<td><form:select path="country">
					  <form:option value="NONE" label="--- Select ---" />
					  <form:options items="${countryList}" />
				       </form:select>
                                </td>
				<td><form:errors path="country" cssClass="error" /></td>
			</tr>
			<tr>
				<td>Java Skills :</td>
				<td><form:select path="javaSkills" items="${javaSkillsList}"
					multiple="true" /></td>
				<td><form:errors path="javaSkills" cssClass="error" /></td>
			</tr>

			<tr>
				<td colspan="3"><input type="submit" /></td>
			</tr>
		</table>
	</form:form>

</body>
</html>

Use JSTL to display submitted value.

File : CustomerSuccess.jsp


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

<html>
<body>
	<h2>Spring's form select, option, options example</h2>

	Country : ${customer.country}
	<br /> Java Skills : ${customer.javaSkills}
	<br />

</body>
</html>

5. Spring Bean Configuration

Link it all ~


<beans xmlns="http://www.springframework.org/schema/beans"
	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-2.5.xsd">

  <bean
  class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />

	<bean class="com.mkyong.customer.controller.DropDownBoxController">
		<property name="formView" value="CustomerForm" />
		<property name="successView" value="CustomerSuccess" />

		<!-- Map a validator -->
		<property name="validator">
			<bean class="com.mkyong.customer.validator.DropDownBoxValidator" />
		</property>
	</bean>

	<!-- Register the Customer.properties -->
	<bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="message" />
	</bean>

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/pages/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
</beans>

6. Demo

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

SpringMVC-DropDownBox-Example-1

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

SpringMVC-DropDownBox-Example-2

If the form is submitted successfully, just display the submitted dropdown box values.

SpringMVC-DropDownBox-Example-3

Download Source Code

Download it – SpringMVCForm-DropDownBox-Example.zip (10KB)

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
44 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
John
11 years ago

How is this file being accessed through dropdownbox.htm? I don’t understand where this mapping is coming from because I’ve dug through the code and there isn’t anything relating to dropdownbox or htm.

Thanks.

Stanic Ng
7 years ago

Thanks for the tutorial. I have a problem showing the item/description of the selected value in the view page. Like the CustomerSuccess.jsp page is display the value of the dropdown. How can i display the item/description instead of value. For example, the country field diaplay MY instead of Malaysia.

dell ket
8 years ago

hello Mkyong, can you post an example which gives information about how to populate a dropdown and retrieve values selected in a multiple select dropdown on form submit.

Johaness
9 years ago

It doesnt works this way.

Gb Pics
12 years ago

Thanks for this nice Tutorial. I have a question regarding the multiple select. If a User have the ability to select mor than one value how can I recieve a list of object so that I can map them to my database. Like I understand it here we only get back on Object so it only works if one value is selected right?

Madhu
12 years ago

Hi,

Good example for Select option. I am new to Springs. I am working on Spring form I am getting an error

2011-10-05 22:27:14,971 [ERROR] [http-0.0.0.0-8080-1] org.springframework.web.servlet.tags.form.SelectTag – Neither BindingResult nor plain target object for bean name ‘categoryFinder’ available as request attribute
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘categoryFinder’ available as request attribute.

In my JSP I have given the commandName correctly. The name I have given is what I am passing from the controller. In controller I am passing ModelAndView(“”,”categoryFinder”,categoryFinder). This I am passing from get as well as in Post as I need same page for multiple entries.

Also when using select option how to set the default value and when passing the value from controller, I want to display that as default value.

could you help me on this.

Thanks in advance
Madhu

shan
10 years ago
Reply to  Madhu

I m geeting same problem..did you find the solution?

RamZ
10 years ago
Reply to  shan

Getting the same problem. let me know how u resolved it….

Anil
12 years ago

mkyong can we implement the same using MultiActionController & how?

utsav kakadiya
7 years ago
Reply to  mkyong

when i am use

it display like that:”com.utsav.Model.countryModel@68a61b83″

nambi
13 years ago

I want to display a drop-down box, and select an option on that drop-down box.
The selected value will differ each time the page is loaded, based on the user.

Can you please explain in more detail how it can be accomplished?

Santhosh
13 years ago
Reply to  nambi

Were you able to find a solution to select value that differs each time the page is loaded? I’m encountering a similar problem. Your reply would be helpful?

NagaSai
2 years ago

how to dynamically pass the list values rather than hardcoding in the controllers.

Cristian
4 years ago

where is dropdownbox.htm?????

Vishnu G K
5 years ago

I have a requirement, like in a form:select it is showing a number of 20 rows out of 24, would there be an option to make it visible 24 without scroll? I have tried size and height which didn’t work, it should show as a drop down without scroll basically.

Alex Smith
6 years ago

The downloaded example doesnt even have the spring config file.

Alex Smith
6 years ago

This does not work. I have downloaded it and ran it fresh and i get the following error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping#0’ defined in ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.mkyong.customer.controller.DropDownBoxController] for bean with name ‘com.mkyong.customer.controller.DropDownBoxController#0’ defined in ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.mkyong.customer.controller.DropDownBoxController

Please help.

Mostafa Zeinali
6 years ago
Reply to  Alex Smith

THANK YOU!! The referenceData method is NEVER called!! The form backing controller needs to return a MAV with customer as an object on it and also mav.addObject(“countryList”, referenceData()); This shows the “keys” of the map in the combo. How to change it to values, no fking clue

Ucup Timposu
8 years ago

do you have example dropdown box for relation table ?

Lewis Florez R
8 years ago

how make select dependent de other for example country state where state have Long id and String name, do you have any example?

Elden Caro Granda
9 years ago

hello with which version of java what made the project go?

hola con que version de java lo haz realizado el proyecto?

Janny
9 years ago

Hello, i am new in Spring, please help me, why do we need “formView” and “succesessView” in spring bean configuration?

miha
9 years ago

Ic not multipl select bean

public class Customer{

String country;
String javaSkills; //this do bi multiple select possible List

idle
9 years ago

??????????????????????????

sumit Deshpande
10 years ago

Where is the mapping for dropdownbox.htm. I dig out the whole code but didnot fin anything.If I want to change the mapping from where can I achieve this??

RamZ
10 years ago

Neither BindingResult nor plain target object for bean name ‘customerForm’ available as request attribute. Am getting above exception when i implemented the same. kindly help me.

Hieu
10 years ago

How can I display “China” instead of “CHINA” on the last image of this tutorial?

Java
10 years ago

Could please make it work for edit version. I am able to get it working for add.
Values selected are going to join table.

But for the edit screen not able to show selected values in multi select.
Any solution?

lucho
11 years ago

as does the same with “Spring MVC 3.0”?

Breed Hansen
11 years ago

Hello,

I have a question. Is it possible to send object to spring form and get object from form?

Anji
11 years ago

Hi I have one qstn, If i submit my form ,based on some Spring form values it should go to different jsps. For example if I provide XXX value for one of Spring Form field it should go to SOMEXXX.jsp and similarly if i Provide YYY Value for that field it should go to SOMEYYY.jsp. Can u pls help me how to do that ?

Bilder
11 years ago

i don’t want to import, i want to buy here in Ecuador direct from the big importers of electronics, mp3, video cameras, etc

GB
11 years ago

Thanks for this nice Tutorial! It helped me a lot.

GB
11 years ago

Thanks for this nice Tutorial.

thanooj
11 years ago

How & where to set default dropdown value using Spring based tag?
i mean, i have a Spring based ‘Gender’ tag which provide 2 options: male and female, but by default male whould be selected.
in this case, could you please help…
How to set default value for Spring based tag.