Open In App

Spring – MVC Form Drop-Down List

Last Updated : 25 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn about the Spring MVC Dropdown list. We will create a basic Spring MVC project in Spring tool suite(STS) to make a dropdown list using form:select tag.

spring-form.tld

We can use Java Server Pages (JSPs) as a view component in Spring Framework. To help you implement views using JSP, the Spring Framework provides form tag library namely spring-form.tld with some tags for evaluating errors, setting themes, formatting the fields for inputting and outputting internationalized messages.

‘select’ tag

The ‘select’ is one of the tag provided by the spring-form.tld library. It renders an HTML ‘select’ element and supports data-binding to the selected option. We can directly use the select tag to display the dropdown values or we can use the option tag also.

Below are the various attributes available in ‘select’ tag.

Attributes in ‘select’ tag

A. HTML Standard Attributes: HTML Standard attributes are also called as global attributes that can be used with all HTML elements.

Name Description
accesskey To specify a shortcut key to activate/focus on an element.
id To specify a unique ID for the element.
dir To specify text direction of elements content.
lang To specify the language of the content.
tabindex To specify tabbing order of an element.
title To specify extra information about the element.

B. HTML Event Attributes: HTML Event Attributes are used to trigger a function when a particular event occurred on the element.

Name Description
onblur To execute a javascript function when a user leaves the text field.
onchange To execute a javascript function when a user changes the text.
onclick To execute a javascript function when the user clicks on the element.
ondblclick To execute a javascript function when the user double click on the element.
onfocus To execute a javascript function when the user focuses on the text box.
onkeydown To execute a javascript function when the user is pressing a key on the keyboard.
onkeypress To execute a javascript function when the user presses the key on the keyboard.
onkeyup To execute a javascript function when the user is releasing the key on the keyboard.
onmousedown To execute a javascript function when the user is pressing a mouse button.
onmousemove To execute a javascript function when the user is moving the mouse pointer.
onmouseout To execute a javascript function when the user is moving the mouse pointer out of the field.
onmouseover To execute a javascript function when the user is moving the mouse pointer onto the field.
onmouseup To execute a javascript function when the user is releasing the mouse button.

C. HTML Optional Attributes:

Name Description
cssClass To specify a class name for an HTML element to access it.
cssErrorClass Used when the bounded element has errors.
cssStyle To add styles to an element, such as color, font, size etc.
disabled To specify the element to be disabled or not.
multiple A boolean attribute to specify user can select multiple values.
size To specify the number of visible options in a drop-down list.

D. Other HTML Attributes:

Name Description
htmlEscape To enable/disable HTML escaping of rendered values
itemLabel To specify the name of the property that is mapped to the inner text of the ‘option’ tag.
items The Collection, Map or array of objects used to generate the inner ‘option’ tags.
itemValue To specify the name of the property mapped to ‘value’ attribute of the ‘option’ tag
path To specify the path to the property for binding the data.

Spring MVC Application

We will be creating the below application:

Spring MVC Dropdown Example

Steps to Create an Application

  1. Create a Spring MVC project in Spring Tool Suite.
  2. In STS, while creating the project based on the developer selection, it will download all the required maven dependencies, *.jar, lib files and it will provide an embedded server.
  3. Below is the final project structure of the Spring MVC project after creating *.java and *.jsp files also.

Project Structure

Implementation: Files to be created are as follows:

  1. SelectBean.java – Bean class – To define the field properties and getter/setter methods of the properties.
  2. SelectController.java – Controller class – To process the user request and generate the output.
  3. select.jsp – Jsp file to interact with the user for the input.
  4. selectSummary.jsp – Jsp file to display the output after processing to the user.

A. FIle: select.jsp

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome Page</title>
</head>
<body>
    <h1>Welcome to GeeksforGeeks!</h1>
 
    <form:form action="submit" method="post" modelAttribute="select">
        <table>
            <tr>
                <td><form:label path="name">Enter your name: </form:label></td>
                <td><form:input path="name" /></td>
            </tr>
            <tr>
                <td><form:label path="education">Select your highest education: </form:label></td>
                <td><form:select id="highestEdu" path="education"
                        items="${educationDetails}" size="2"
                        cssStyle="font-family:monospace" onclick="color()">
                    </form:select></td>
            <tr>
                <td><form:label path="subject">Select the subject: </form:label></td>
                <td><form:select path="subject" title="SUBJECT" multiple="true"
                        size="3">
                        <form:option value="Java" label="Java Programming" />
                        <form:option value="SQL" label="SQL language" />
                        <form:option value="Python" label="Python programming" />
                        <form:option value="JavaScript" label="JavaScript" />
                        <form:option value="PHP" label="PHP" />
                    </form:select></td>
            </tr>
            <tr>
                <td><form:button>Submit</form:button></td>
            </tr>
        </table>
    </form:form>
    <script type="text/javascript">
     
        function color(){
            document.getElementById("highestEdu").style.backgroundColor = "palegreen";
        }
     
     
    </script>
</body>
</html>


 
 

  • This is the welcome page when the application runs.
  • To use the Spring tags, we need to specify below spring tag library URI in the Jsp,

 

HTML




<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>


 
 

  • If you are not including this tag library, then the container does not understands the form tags, those will become unknown tags for it.
  • For proper structure of the fields, we are using table tag.
  • As we discussed above, we can create a dropdown list using select tag only or we can also use option tag.
  • Generally, option tag will be used when we are providing the values individually.

 

B. File: SelectBean.java

 

HTML




package com.geek.app;
 
public class SelectBean {
 
    public String name;
    public String education;
    public String subject;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getEducation() {
        return education;
    }
 
    public void setEducation(String education) {
        this.education = education;
    }
 
    public String getSubject() {
        return subject;
    }
 
    public void setSubject(String subject) {
        this.subject = subject;
    }
 
}


  • This is the java bean to define all the properties to store the values
  • And their getter/setter methods to get and set the values of the properties.

C. SelectController.java

Java




// Java Program to Illustrate SelectController Class
 
package com.geek.app;
 
// Importing required classes
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
// Annotation
@Controller
 
// Class
public class SelectController {
 
    // Annotation
    @RequestMapping(value = "/")
 
    public String view(Model model)
    {
 
        SelectBean sel = new SelectBean();
        model.addAttribute("select", sel);
 
        return "select";
    }
 
    // Annotation
    @ModelAttribute("educationDetails")
 
    public List<String> educationDetailsList()
    {
        List<String> educationList = Arrays.asList(
            "10th class", "Intermediate", "Graduation",
            "Post Graduation");
 
        return educationList;
    }
 
    // Annotation
    @RequestMapping(value = "/submit",
                    method = RequestMethod.POST)
 
    public String
    submit(@ModelAttribute("select") SelectBean select)
    {
        return "selectSummary";
    }
}


 
 

  • This is the controller class where it process the methods based on the mapping of the request URLs.
  • Here, @Controller, conveys to the container that this class is the spring controller class.
  • The annotation, @RequestMapping, maps the request URL’s to the specified method based on the value provided.
  • The annotation @ModelAttribute, to bind a method parameter or method return value to the named model attribute.

 

D. File: selectSummary.jsp

 

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Summary page</title>
</head>
<body>
    <h3>Hello ${select.name}, details submitted successfully!!</h3>
 
    <span>Highest Education: </span>
    <span>${select.education}</span>
    <br>
    <span>Subject Selected: </span>
    <span>${select.subject}</span>
 
</body>
</html>


 
 

This is the output page, where we are just displaying the values selected by the user as input.

 

Execution:

  • After creating all the required java and jsp files, run the project on the server.
  • Right on the Project, Run as -> Run on the server.
  • Select the server in the localhost to run the application.
  • Open the URL: http://localhost:8080/app/ in the browser to get the below screen.

Welcome page – select.jsp

  • As we specified different attributes to the select tag, that functionality can be seen here.

Functionality of Attributes

  • Input all the fields and click on submit button.

Enter the values to submit

  • Once the page is submitted, the controller class process the URL request and executes the respective method and displays below output.

Output – selectSummary.jsp

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads