Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring - MVC Form Drop-Down List
Next article icon

Spring - MVC Form Drop-Down List

Last Updated : 25 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
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.

NameDescription
accesskeyTo specify a shortcut key to activate/focus on an element.
idTo specify a unique ID for the element.
dirTo specify text direction of elements content.
langTo specify the language of the content.
tabindexTo specify tabbing order of an element.
titleTo 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.

NameDescription
onblurTo execute a javascript function when a user leaves the text field.
onchangeTo execute a javascript function when a user changes the text.
onclickTo execute a javascript function when the user clicks on the element.
ondblclickTo execute a javascript function when the user double click on the element.
onfocusTo execute a javascript function when the user focuses on the text box.
onkeydownTo execute a javascript function when the user is pressing a key on the keyboard.
onkeypressTo execute a javascript function when the user presses the key on the keyboard.
onkeyupTo execute a javascript function when the user is releasing the key on the keyboard.
onmousedownTo execute a javascript function when the user is pressing a mouse button.
onmousemoveTo execute a javascript function when the user is moving the mouse pointer.
onmouseoutTo execute a javascript function when the user is moving the mouse pointer out of the field.
onmouseoverTo execute a javascript function when the user is moving the mouse pointer onto the field.
onmouseupTo execute a javascript function when the user is releasing the mouse button.

C. HTML Optional Attributes:

NameDescription
cssClassTo specify a class name for an HTML element to access it.
cssErrorClassUsed when the bounded element has errors.
cssStyleTo add styles to an element, such as color, font, size etc.
disabledTo specify the element to be disabled or not.
multipleA boolean attribute to specify user can select multiple values.
sizeTo specify the number of visible options in a drop-down list.

D. Other HTML Attributes:

NameDescription
htmlEscapeTo enable/disable HTML escaping of rendered values
itemLabelTo specify the name of the property that is mapped to the inner text of the 'option' tag.
itemsThe Collection, Map or array of objects used to generate the inner 'option' tags.
itemValueTo specify the name of the property mapped to 'value' attribute of the 'option' tag
pathTo 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


 


Next Article
Spring - MVC Form Drop-Down List

Y

yaminitalisetty
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • Java-Spring
  • Java-Spring-MVC
Practice Tags :
  • Java

Similar Reads

    How to Resolve WEB xml is missing and failOnMissingWebXml is set to true in Eclipse/STS?
    Eclipse/STS IDE is generally used to develop Spring applications and what happens is whenever we are creating a simple Maven project and if the web.xml is missing or you have deleted that file then you may encounter this problem inside the pom.xml file corresponding to which do refer to the below im
    2 min read
    Spring MVC Application Without web.xml File
    Spring MVC framework enables separation of modules namely Model, View, and Controller, and seamlessly handles the application integration. This enables the developer to create complex applications also using plain java classes. Here we will be creating and running Your First Spring MVC Application,
    4 min read
    Spring - MVC Listbox
    Spring Web MVC framework to demonstrate how to utilize Listbox in forms. Let's start by setting up an Eclipse IDE and then following the steps to create a Dynamic Form-based Web Application utilizing the Spring Web Framework. The items are listed in the Spring MVC form Listbox. This tag creates a se
    4 min read
    Spring MVC - Multiple Resolver Mapping
    Spring MVC Framework provides the feature of View Resolver through which you can map a view to its respective view and render the model in your browser. The View Resolver eliminates the use of view technologies like Velocity and JSP. There are many view resolvers available in spring-like InternalRes
    4 min read
    How to Extract TV Show Details via REST API and Spring MVC?
    REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring MVC is a Web MVC Framework for building web applicat
    9 min read
    Spring MVC File Upload
    Spring MVC provides a robust mechanism for handling file uploads in web applications. Using Spring MVC file upload, developers can easily integrate multipart file handling with the CommonsMultipartResolver. This article covers how to upload files in Spring MVC, configure MultipartResolver, and manag
    6 min read
    Spring MVC - Tiles
    Spring provides functionality for integrating with the Apache Tiles framework. With the help of spring tiles support, we can easily manage the layout of the Spring MVC application. Benefits of Spring MVC's Tiles support: The following are some of the primary benefits of Spring MVC Tiles 3 Integratio
    4 min read
    Spring MVC - Text Box
    To begin, make sure you have a working Eclipse IDE installed and follow the steps below to create a Spring Web Framework-based Dynamic Form-based Web Application. Steps to create TextBox in Spring MVC: Create a SpringMVCTextField project in the com.geeksforgeeks package.Under the com.geeksforgeeks p
    3 min read
    Spring MVC - Multiple Controller
    We may construct numerous controllers at once in Spring MVC. Each controller class must be annotated with the @Controller annotation. A Spring MVC example with numerous controllers can be found here. The procedure is as follows: In the case of Maven, load the spring jar files or add dependencies.Mak
    2 min read
    Spring MVC - Model Interface
    The Spring Web model-view-controller (MVC) is an open-source framework used to build J2EE web applications. It is based on the Model-View-Controller design pattern and implements the basic features of a core spring framework - Dependency Injection. It is designed around a 'DispatcherServlet' that di
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences