Sunday, January 5, 2020

Spring MVC Dropdown Example Using Select, Option And Options Tag

In this post we’ll see how to show dropdown box in a Spring MVC application using select, option and options tag provided by the form tag library in the Spring MVC framework.

Spring MVC Project structure using Maven


<form:select> tag in Spring MVC

This tag renders an HTML 'select' element. It supports data binding using the "items" property. Select tag also supports use of nested option and options tag.

The items attribute is typically populated with a collection or array of item objects. If itemValue and itemLabel attributes are specified then these attributes refer to the bean properties of those item objects otherwise the item objects value itself is used. You can also 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.

One advantage of using select tag is that it has an attribute multiple when set to true you can select multiple values from the list box. One drawback of using only select tag is that you can’t give any display only value like “-please select-” for that you’ll have to use option tag.

Spring MVC dropdown example using select tag

For the Spring MVC form dropwdown example let’s assume there is a class UserPreferences that stores the selected value of the dropdowns. There are two set of dropdowns in the JSP and there are two properties in the UserPreferences bean class to store the selected options.

Spring MVC dropdown example – Model Class

public class UserPreferences {

 private String exercise;
 private String country;
 public String getExercise() {
  return exercise;
 }
 public void setExercise(String exercise) {
  this.exercise = exercise;
 }
 public String getCountry() {
  return country;
 }
 public void setCountry(String country) {
  this.country = country;
 }
}

Spring MVC dropdown example using select tag – View

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<title>Spring MVC dropdown example using select tag</title>
</head>
<body>
<h3>Spring MVC dropdown example using select tag</h3>
<form:form method="POST" action="showPreferences" modelAttribute="preferences">

    <table>
        <tr>
            <td><b>Country:</b></td>
        
            <td><form:select path="country" items="${countryOptions}"/></td>
        </tr>
        <tr>
            <td><b>Favorite Exercise:</b></td>
        
            <td><form:select path="exercise" items="${exerciseList}" multiple="true"/></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit"></td>
        </tr>
    </table>
</form:form>
</body>
</html>

As you can see <form:select> tag is used with the items property. The values used with the items property in the JSP countryOptions and exerciseList should be available as a model attribute containing String of values to be shown in the dropdown.

With one of the <form:select> tag multiple attribute set as true is also used. This will enable multiple selections.

There is another JSP that is used to display the values selected in the dropdown and listbox.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<title>User Preferences</title>
</head>
<body>
<h3>Spring MVC dropdown example using select tag</h3>
Country: ${preferences.country}<br/>
Favorite exercise: ${preferences.exercise}

</body>
</html>

Spring MVC dropdown example – Controller class

public class UserController {
    
    @RequestMapping(value = "/showUser", method = RequestMethod.GET)
    public String showUser(Model model) throws Exception{
        UserPreferences pref = new UserPreferences();    
        // Default Value for country dropdown
        pref.setCountry("IN");
    
        // Preparing values for "Country" Dropdown
        Map<String, String> countryMap = new HashMap<>();
        countryMap.put("AR", "Argentina");
        countryMap.put("IN", "India");
        countryMap.put("JP", "Japan");
        countryMap.put("US", "United States");
        countryMap.put("SG", "Singapore");
        model.addAttribute("countryOptions", countryMap);
        model.addAttribute("preferences", pref);
        return "user";
    }
    
    @RequestMapping(value = "/showPreferences", method = RequestMethod.POST)
    public String showPreferences(@ModelAttribute("preferences") UserPreferences preferences, Model model) throws Exception{
        model.addAttribute("preferences", preferences);
        return "showPreferences";
    }
    
    // List for "Favorite Exercise" dropdown
    @ModelAttribute("exerciseList")
    public List<String> getExerciseList(){
        List<String> exerciseList = new ArrayList<>();
        exerciseList.add("Aerobic");
        exerciseList.add("Anaerobic");
        exerciseList.add("Flexibility Trng");
        return exerciseList;
    }
}

In the Controller class, showUser() method is used to handle the /showUser request path. Method returns the view name as “user” which resolves to /WEB-INF/jsp/user.jsp JSP.

As you can see exerciseList and countryOptions which are used in the JSP to show dropdown options are set here as model attribute. Default value is also set for one of the dropdown so that the value is pre-selected in the JSP.

Another handler method showPreferences() handles the request when submit button is clicked in the user.jsp.

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/spring-mvc/showUser

Spring MVC dropdown using select tag

As you can see India is already selected as the property was set in the bean object. Since multiple attribute is set as true for the other select tag so multiple values can be selected. Clicking the submit button displays the selected values.

Spring MVC dropdown example

<form:option> tag in Spring MVC

This tag renders an HTML 'option'. If you want to hardcode dropdown values with in the JSP itself then you can use option tag.

Spring MVC dropdown example using option tag

If we have to create the same view using option tag as created above using the select tag where there are two drop downs and one of them is rendered as a listbox by using multiple=”true” attribute. In this case dropdown options are hardcoded with in the JSP itself.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<title>Spring MVC dropdown example using option tag</title>
</head>
<body>
<h3>Spring MVC dropdown example using option tag</h3>
<form:form method="POST" action="showPreferences" modelAttribute="preferences">

    <table>
        <tr>
            <td><b>Country:</b></td>
        
            <td>
                <form:select path="country">
                    <form:option value="AR" label="Argentina"/>
                    <form:option value="IN" label="India"/>
                    <form:option value="JP" label="Japan"/>
                    <form:option value="US" label="United States"/>
                    <form:option value="SG" label="Singapore"/>
                </form:select>
            </td>
        </tr>
        <tr>
            <td><b>Favorite Exercise:</b></td>
            <td>
                <form:select path="exercise" multiple="true">
                    <form:option value="Aerobic"/>
                    <form:option value="Anaerobic"/>
                    <form:option value="Flexibility Trng"/>
                </form:select>
            </td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit"></td>
        </tr>
    </table>
</form:form>
</body>
</html>

<form:options> tag in Spring MVC

This tag renders a list of HTML 'option' tags. Options tag also let you provide options at run time rather than hardcoding them. You pass in an Array, a List or a Map containing the available options in the "items" property.

Spring MVC dropdown example using options tag

In this example Model class and Controller class are the same as used above.

User.jsp with changes for options tag is as below.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<title>Spring MVC dropdown example using select tag</title>
</head>
<body>
<h3>Spring MVC dropdown example using select tag</h3>
<form:form method="POST" action="showPreferences" modelAttribute="preferences">

    <table>
        <tr>
            <td><b>Country:</b></td>
        
            <td>
                <form:select path="country">
                    <form:option value="-" label="-Please Select-"/>
                    <form:options items="${countryOptions}"/>            
                </form:select>
            </td>
        </tr>
        <tr>
            <td><b>Favorite Exercise:</b></td>
            <td>
                <form:select path="exercise" multiple="true">
                    <form:options items="${exerciseList}"/>    
                </form:select>
            </td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit"></td>
        </tr>
    </table>
</form:form>
</body>
</html>

Deploying and testing the application

Once the application is deployed to Tomcat server it can be accessed using the URL- http://localhost:8080/spring-mvc/showUser

Spring MVC dropdown using options tag

Now no default value is set in the Controller class so first option “Please Select” is displayed. Since multiple is set as true for the other select tag so multiple values can be selected.

After selecting some values.

Showing the selected values once submit button is clicked.

Spring MVC dropdown

Reference- https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-view-jsp-formtaglib

That's all for this topic Spring MVC Dropdown Example Using Select, Option And Options Tag. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC Checkbox And Checkboxes Form Tag Example
  2. Spring MVC Dot (.) Truncation Problem With @PathVariable Annotation
  3. Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice
  4. Spring MVC Generate Response as JSON Example
  5. Spring Transaction Management JDBC Example Using @Transactional Annotation

You may also like-

  1. Difference Between @Controller And @RestController Annotations in Spring
  2. Insert\Update Using JDBCTemplate in Spring Framework
  3. Spring Bean Life Cycle
  4. How to Read Properties File in Spring Framework
  5. Java Collections Interview Questions
  6. How to Sort ArrayList in Java
  7. static Method Overloading or Overriding in Java
  8. How to Untar a File - Java Program