...

/

Spring MVC Form Tags - Part 2

Spring MVC Form Tags - Part 2

Learn about diverse form tags in a Spring MVC application.

In this lesson, we will add more items to the add-player-form in order to demonstrate more Spring MVC form tags.

<form:select> tag

We will add a drop-down list to our form, to let the user select the player’s country. For this, first we will update the Athlete class to add a country field along with getter and setter methods for the field.

@Component
public class Athlete {
private String lastName;
private String country;
//...
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Adding country attribute to the Athlete class

In traditional HTML form tags, a drop-down list is created using a <select> with multiple <option> tags as follows:

Press + to interact
<select name="playerCountry">
<option>Australia</option>
<option>France</option>
<option>Serbia</option>
<option>Switzerland</option>
<option>United States of America</option>
</select>

The <select> tag lets us define a list of <option> elements that users can select from. Each option is specified with a value attribute, and the text between the opening and closing <option> tags is displayed to the user. While the syntax is straightforward and effective for simple forms, it requires manual handling of the form data on the server side.

Spring MVC’s equivalent tags are <form:select> and <form:option> with path specifying the bean property to which the drop-down list binds to.

We will use Spring MVC form tags to add a drop-down list to the add-player-form.jsp as follows:

Press + to interact
<form:select path="country">
<form:option value="AUT" label="Austria"/>
<form:option value="FRA" label="France"/>
<form:option value="SRB" label="Serbia"/>
<form:option value="SUI" label="Switzerland"/>
<form:option value="USA" label="United States of America"/>
</form:select>

The <form:select> tag simplifies the creation and management of dropdown menus by automatically binding the selected value to a model attribute. path="country" maps the drop-down list to the country field in the Athlete class. The <form:option> tag defines individual options within the <form:select> tag. It contains value and label ...