Enterprise Java

Spring MVC: form handling vol. 5 – select, option, options tags

Drop-down lists are the one of the most frequent elements in web forms. In HTML you can create such control using appropriate tags: < form:select > – parent tag of drop-down list and < form:option > – child tag of < form:select > tag. Spring MVC tag library has its own solution for the drop-down lists. In this post I will write about < form:select >, < form:option >, and < form:options > tags.spring-mvc-drop-down

In the previous articles about form handling using Spring MVC I have made an overview of cases when we need to bind text field, check-boxes or radio buttons with a java object. Almost all steps will be repeated for the select drop-down list element. Further I will examine three situations with drop-down lists in context of binding it with java object using Spring MVC tag library. The first case will be about form:select tag with values based on java.util.Map, the second example will be about usage of form:select tag in conjunction with form:option tags, the third example will be about usage of form:select tag in conjunction with form:options tag.

Every example will have the same result jsp page, so only the form pages will be different and controllers for them. Setup of configuration will be omitted because it was explained in the one of previous articles.

Spring MVC select tag

Let’s assume that user of web application can select a producer of mobile phone (e.g. HTC, SAMSUNG, IPHONE etc). We can implement this in several ways using the Spring MVC form tag library.

Domain model:

public class Smartphone {

	private String phone;

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

}

This class will be binded to the forms.

SmartphoneController:

...
	@RequestMapping(value="/phone-page")
	private ModelAndView selectTag() {
		ModelAndView mav = new ModelAndView("phone-form");

		Map< String, String > phones = new HashMap();
		phones.put("samsung", "SAMSUNG");
		phones.put("nokia", "NOKIA");
		phones.put("iphone", "IPHONE");

		mav.addObject("phonesMap", phones);
		mav.addObject("smartphone", new Smartphone());

		return mav;
	}

	@RequestMapping(value="/phone-result")
	private ModelAndView processPhone(@ModelAttribute Smartphone smartphone) {
		ModelAndView mav = new ModelAndView("phone-result");
		mav.addObject("smartphone", smartphone);		
		return mav;
	}
...

In the selectTag() method I create a Map with values which will be displayed on page with drop-down. The second method processPhone(@ModelAttribute Smartphone smartphone) will be used as a shared end point for the all examples.

JSP for this example:

<h1>Phone page</h1>
Select phone:
<form:form method="POST" commandname="smartphone" action="phone-result.html">
<table>
    <tbody><tr>
    <td>
	    <ul>
	    	<form:select path="phone" items="${phonesMap}">
	    </form:select></ul>
    </td>
    </tr>
    <tr>
        <td>
            <input value="Submit" type="submit">
        </td>
    </tr>
</tbody></table>  
</form:form>

Spring-mvc-select

That’s it

Spring MVC option tag

The second example will use hardcoded value of the < form:option > tag.

Controller:

...
	@RequestMapping(value="/phone-option-page")
	private ModelAndView optionTag() {		
		return new ModelAndView("phone-option-form", "smartphone", new Smartphone());
	}
...

Pay attention to the JSP:

<h1>Phone page</h1>
Select phone:
<form:form method="POST" commandname="smartphone" action="phone-result.html">
<table>
    <tbody><tr>
    <td>
	    <ul>
	    	<form:select path="phone">
	    		<form:option value="samsung">SAMSUNG</form:option>
	    		<form:option value="nokia">NOKIA</form:option>
	    		<form:option selected="selected" value="htc">HTC</form:option>
	    		<form:option value="iphone">IPHONE</form:option>
	    	</form:select>
	    </ul>
    </td>
    </tr>
    <tr>
        <td>
            <input value="Submit" type="submit">
        </td>
    </tr>
</tbody></table>  
</form:form>

Spring MVC options tag

The last example demonstrates how work with < form:options > tag.

Controller:

...
	@RequestMapping(value="/phone-options-page")
	private ModelAndView optionsTag() {
		ModelAndView mav = new ModelAndView("phone-options-form");

		Map< String, String > phones = new HashMap();
		phones.put("samsung", "SAMSUNG");
		phones.put("nokia", "NOKIA");
		phones.put("iphone", "IPHONE");
		phones.put("bberry", "BLACKBERRY");
		phones.put("htc", "HTC");

		mav.addObject("phonesMap", phones);
		mav.addObject("smartphone", new Smartphone());

		return mav;
	}
...

And the appropriate JSP:

...
<h1>Phone page</h1>
Select phone:
<form:form method="POST" commandname="smartphone" action="phone-result.html">
<table>
    <tbody><tr>
    <td>
	    <ul>
	    	<form:select path="phone">
		    	<form:option value="-" label="--Select phone">
	            <form:options items="${phonesMap}">
	    	</form:options></form:option></form:select>
	    </ul>
    </td>
    </tr>
    <tr>
        <td>
            <input value="Submit" type="submit">
        </td>
    </tr>
</tbody></table>  
</form:form>
...

As specified in official Spring Documentation you can use any kind of java objects with appropriate getters and setters for the form:options tag: The items attribute is typically populated with a collection or array of item objects. itemValue and itemLabel simply refer to bean properties of those item objects, if specified; otherwise, the item objects themselves will be stringified. Alternatively, you may specify a Map of items, in which case the map keys are interpreted as option values and the map values correspond to option labels. If itemValue and/or itemLabel happen to be specified as well, the item value property will apply to the map key and the item label property will apply to the map value.

Summary

Each of these examples is convenient in particular situation and should be used rationally. The < form:option > tag can be used in a small projects where you don’t need a big quantity of options, the < form:options > should be used when you store values of a drop-down in the database or when you need to generate the values in runtime. Source code of the tutorial you can find on GitHub.
 

Alexey Zvolinskiy

Alexey is a test developer with solid experience in automation of web-applications using Java, TestNG and Selenium. He is so much into QA that even after work he provides training courses for junior QA engineers.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

11 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Yu-Cheng Wang
Yu-Cheng Wang
10 years ago

nice article

Debojit
Debojit
10 years ago

Its really a good post. Liked it !!

David
David
10 years ago

Great Post. It served as a great refresher on working with form submission/data binding with Spring MVC. Good stuff!

Mike
Mike
10 years ago

In the very last example, how would you make one of the options (for example, HTC) the default value?

Inyavic
10 years ago

This is really a well detailed tutorial on form handling. I’m so grateful for it.

Paulo
Paulo
9 years ago

Congratulations man, but I have one question
How to do get the list value on controller class?
When I dispatch form to my controller, it arrives null values. (using list attribute of my POJO).
Tks!

Ali
Ali
8 years ago
Reply to  Paulo

In case of list, declare list in your pojo like
private List ids
// getter and setter

then you will get list of ids.

npk
npk
9 years ago

in case of list…how would i get the selected values in the controller?

M Abdul Munaf
M Abdul Munaf
9 years ago

helped me a lot…………. Thank you very much

Jack
Jack
9 years ago

OK, this is all over good stuff. But in all of these examples the options are hard-coded. What if, I have a database, and the database takes in values say for ice cream flavors. Right now it has vanilla, chocolate, strawberry, later on someone enters in rocky road.

I want those to populate the drop down list.

How do I go about doing that?

Jack
Jack
9 years ago

How would one go about pulling dropdown options from a DB column without hard coding it? All these examples have the options hard coded.

Back to top button