Alexey Zvolinskiy

About 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.

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.
 

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

6 Responses to "Spring MVC: form handling vol. 5 – select, option, options tags"

  1. Yu-Cheng Wang says:

    nice article

  2. Debojit says:

    Its really a good post. Liked it !!

  3. David says:

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

  4. Mike says:

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

  5. Inyavic says:

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

  6. Paulo says:

    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!

Leave a Reply


+ 6 = ten



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close