The Wayback Machine - https://web.archive.org/web/20241127230319/https://www.geeksforgeeks.org/spring-mvc-listbox/
Open In App

Spring – MVC Listbox

Last Updated : 25 Mar, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Spring -MVC Framework

The items are listed in the Spring MVC form Listbox. This tag creates a select element in HTML. It allows you to bind data to the element you’ve chosen.

Syntax:

<form:select path="name">  

Here are some more tags that may be used to narrow down the selections.

A. Option tag: The HTML option tag is generated by this tag. Each tag has a value that the user can choose from.

<form:option value="abc" label="xyz"/>  

B. Options tag: A list of HTML option tags is generated by this tag. Each tag has a list of components that the user has chosen.

<form:options items="${elementList}" itemValue="abc" itemLabel="xyz"/>  

Spring MVC – Listbox

The project Structure is as follows:

Implementation:

Step 1: Add dependencies to the pom.xml file.

File: pom.xml

XML




  <modelVersion>4.0.0</modelVersion>
  <groupId>com.geeksforgeeks</groupId>
  <artifactId>SpringMVC</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVC Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
      
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.1.RELEASE</version>
</dependency>
  
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jasper</artifactId>
    <version>9.0.12</version>
</dependency>
<dependency>  
    <groupId>javax.servlet</groupId>  
    <artifactId>servlet-api</artifactId>  
    <version>3.0-alpha-1</version>  
</dependency>
  
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
  
  </dependencies>
  <build>
    <finalName>SpringMVC</finalName>
  </build>
</project>


Step 2: Create the bean class

File: Reservation.java

Java




// Java Program to Illustrate Reservation Class
  
package com.geeksforgeeks;
  
// Class
public class Reservation {
    // Class data members
    private String firstName;
    private String lastName;
    private String Gender;
    private String[] Food;
    private String cityFrom;
    private String cityTo;
  
    // Constructor
    public Reservation() {}
  
    // Getters and Setters
    public String getFirstName() { return firstName; }
    public void setFirstName(String firstName)
    {
        // this keyword refers to current instance itself
        this.firstName = firstName;
    }
  
    // Getters and Setters
    public String getLastName() { return lastName; }
    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }
  
    // Getters and Setters
    public String getGender() { return Gender; }
    public void setGender(String gender)
    {
        Gender = gender;
    }
  
    // Getters and Setters
    public String[] getFood() { return Food; }
    public void setFood(String[] food) { Food = food; }
    public String getCityFrom() { return cityFrom; }
    public void setCityFrom(String cityFrom)
    {
        this.cityFrom = cityFrom;
    }
  
    // Getters and Setters
    public String getCityTo() { return cityTo; }
    public void setCityTo(String cityTo)
    {
        this.cityTo = cityTo;
    }
}


Step 3: Create the controller class

File: ReservationController.java

Java




// Java Program to Illustrate ReservationController Class
  
package com.geeksforgeeks;
  
// Importing required classes
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
  
// Annotation
@RequestMapping("/reservation")
@Controller
  
// Class
public class ReservationController {
    @RequestMapping("/bookingForm")
  
    // Method
    public String bookingForm(Model model)
    {
        Reservation res = new Reservation();
        model.addAttribute("reservation", res);
  
        return "reservation-page";
    }
  
    // Annotation
    @RequestMapping("/submitForm")
    // Method
    public String submitForm(@ModelAttribute("reservation")
                             Reservation res)
    {
        return "confirmation-form";
    }
}


Step 4: Provide the entry of controller in the web.xml file

File: web.xml

Java




<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <display-name>SpringMVC</display-name>
   <servlet>  
    <servlet-name>spring</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <load-on-startup>1</load-on-startup>    
</servlet>  
<servlet-mapping>  
    <servlet-name>spring</servlet-name>  
    <url-pattern>/</url-pattern>  
</servlet-mapping>  
</web-app>


Step 5: Define the bean in the XML file

File: spring-servlet.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
    xsi:schemaLocation="
  
    <!-- Add support for component scanning -->
    <context:component-scan base-package="com.geeksforgeeks" />
      
    <!--Add support for conversion, formatting and validation -->
    <mvc:annotation-driven/>
     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>       
     </bean>
</beans>


Step 6: Create the requested page

File: index.jsp

HTML




<!DOCTYPE html>
<html>
<head>
    <title>Railway Reservation System</title>
</head>
<body>
<a href="reservation/bookingForm">GFG Railway Reservation System.</a>
</body>
</html>


Step 7: Create the view components

File: reservation-page.jsp

HTML




<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
    <title>Reservation Form</title>
</head>
<h3>Railway Reservation Form</h3>
<body>
    <form:form action="submitForm" modelAttribute="reservation">
        First name: <form:input path="firstName" />        
        <br><br>
        Last name: <form:input path="lastName" />
        <br><br>
        Gender: 
        Male<form:radiobutton path="Gender" value="Male"/>
        Female<form:radiobutton path="Gender" value="Female"/>
        <br><br>
        Meals:
        BreakFast<form:checkbox path="Food" value="BreakFast"/>
        Lunch<form:checkbox path="Food" value="Lunch"/>
        Dinner<form:checkbox path="Food" value="Dinner"/>
        <br><br>
        Leaving from: <form:select path="cityFrom">
        <form:option value="Delhi" label="Delhi"/>
        <form:option value="Noida" label="Noida"/>
        <form:option value="Amritsar" label="Amritsar"/>
        </form:select>
        <br><br>
        Going to: <form:select path="cityTo">
        <form:option value="Mumbai" label="Mumbai"/>
        <form:option value="Pune" label="Pune"/>
        <form:option value="Nashik" label="Nashik"/>
        </form:select>
        <br><br>
        <input type="submit" value="Submit" />
    </form:form>
</body>
</html>


File: confirmation-page.jsp

HTML




<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<body>
  
<p>Geeksforgeeks reservation is confirmed successfully.</p>
  
First Name : ${reservation.firstName} <br>
Last Name : ${reservation.lastName} <br>
Gender: ${reservation.gender}<br>
Meals: 
<ul>
<c:forEach var="meal" items="${reservation.food}">
<li>${meal}</li>
</c:forEach>
</ul>
Leaving From : ${reservation.cityFrom} <br>
Going To : ${reservation.cityTo}
</body>
</html>


Output:

Click on the link and you will see the following output

Select other Listbox

At the last, this output will be shows



Previous Article
Next Article

Similar Reads

Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
Difference between Spring MVC and Spring Boot
1. Spring MVC : Spring is widely used for creating scalable applications. For web applications Spring provides Spring MVC framework which is a widely used module of spring which is used to create scalable web applications. Spring MVC framework enables the separation of modules namely Model View, Controller, and seamlessly handles the application in
3 min read
Create and Run Your First Spring MVC Controller in Eclipse/Spring Tool Suite
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. The model object can be passed between view and controller using maps. In this article, we will see how to set up a Spring
5 min read
Difference Between Spring MVC and Spring WebFlux
Spring MVCSpring MVC Framework takes on the Model-View-Controller design pattern, which moves around the Dispatcher Servlet, also called the Front Controller. With the help of annotations like @Controller and @RequestMapping, the by-default handler becomes a robust(strong) tool with a diverse set of handling ways. This kind of dynamic kind of featu
5 min read
How to Build a RESTful API with Spring Boot and Spring MVC?
RESTful APIs have become the standard for building scalable and maintainable web services in web development. REST (Representational State Transfer) enables a stateless, client-server architecture where resources are accessed via standard HTTP methods. This article demonstrates how to create a RESTful API using Spring Boot and Spring MVC. We will w
7 min read
Spring MVC – Handling Form Validation with Spring Validator
Form validation is crucial in web applications to ensure that user input is both accurate and appropriate before processing or storing it. In Spring MVC, form validation can be efficiently managed using the Spring Validator interface and annotations. This allows for flexible and robust validation mechanisms that are easy to implement and maintain i
7 min read
Securing a Spring MVC Application with Spring Security
Securing web applications is crucial in today's world, where security threats are prevalent. Spring Security is a powerful, customizable authentication and access-control framework that is part of the larger Spring ecosystem. It helps secure Spring MVC applications by managing authentication, authorization, and other security concerns. This article
7 min read
Spring MVC vs Spring Web Flux: Top Differences
For creating Java-based projects and applications, developers usually have to choose between Spring MVC and Spring WebFlux when using the Spring framework to create web apps. To pick the best framework for their project, developers need to know how each one is different and what features they have. Each framework has its own benefits compared to th
11 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Data Transfer Object (DTO) in Spring MVC with Example
In Spring Framework, Data Transfer Object (DTO) is an object that carries data between processes. When you're working with a remote interface, each call is expensive. As a result, you need to reduce the number of calls. The solution is to create a Data Transfer Object that can hold all the data for the call. It needs to be serializable to go across
8 min read
Spring MVC - Get Probability of a Gender by Providing a Name using REST API
A lot of funful REST API calls are available as open source. Suppose if we like to keep a name to our nears and dears, we can just check that by means of a REST API call and get the gender, what is the probability of being that gender and how many times does it come with it? Relevant REST API call https://api.genderize.io?name=<Provide your desi
7 min read
Spring - MVC Regular Expression Validation
Regular Expression Validation in Spring MVC can be achieved by using Hibernate Validator which is the implementation of Bean Validation API. Hibernate Validator provides @Pattern annotation which is used for regular expression validation. Syntax: @Pattern(regex="", flag="", message="") private String someDataMember; Note that the flag and message a
4 min read
Spring MVC using Java based configuration
Prerequisites: MVC Design Pattern, Spring MVC with JSP ViewSpring 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. The model object can be passed between view and controller using
5 min read
Spring MVC - Get Exchange Rate Values using REST API
People are doing business, and developing software for geographical locations. That means the calculation of a software price will vary globally. During those scenarios, we need to know about the exchange rates for a given currency. Nowadays many open source REST API calls are available and among that there is a call available to get exchange rates
5 min read
Spring - MVC Form Drop-Down List
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 t
7 min read
Spring - MVC Validation
The Spring MVC framework provides us with standard predefined validators to validate user input data in a simple and straightforward way. The Bean Validation API is the popular approach for data validations in Spring applications. Here we will be using the hibernate implementation of the Bean Validation API known as Hibernate Validator. Validation
5 min read
Spring - MVC TextArea
Here we will be learning about the Spring MVC TextArea form tag. We will create a basic Spring MVC project in the Spring tool suite(STS) to get some data from the user using the TextArea form 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
7 min read
Spring - MVC Form Radio Button
Here, we will learn about the Spring MVC radiobutton and radiobuttons tags. We will create a basic Spring MVC project in the Spring tool suite(STS) to create radiobuttons using form:radiobutton and form:radiobuttons tags. 'spring-form.tld' tag libraryIn Spring Framework, we can use Java Server Pages (JSPs) as a view component. From version 2.0, Spr
8 min read
Spring - MVC Form Checkbox
In this article, we will learn about the Spring MVC Checkbox and Checkboxes tags. We will create a basic Spring MVC project in the Spring tool suite(STS) to create checkboxes using form:checkbox and form:checkboxes tags. 'spring-form.tld' tag library In Spring Framework, we can use Java Server Pages (JSPs) as a view component. To implement views us
6 min read
Spring - MVC Form Handling
Prerequisites: Spring MVC, Introduction to Spring Spring MVC is a Model-View-Controller framework, it enables the separation of modules into Model, View, and Controller and uniformly handles the application integration. In this article, we will create a student login form and see how Spring MVC handles form-based web-based applications. Steps to Cr
6 min read
Spring - MVC Form Tag Library
Spring Framework provides spring's form tag library for JSP views in Spring's Web MVC framework. In Spring Framework, we use Java Server Pages(JSP) as a view component to interact with the user. From version 2.0, Spring Framework provides a comprehensive set of data binding-aware tags. These tags are used for handling form elements when using JSP a
14 min read
Spring - MVC Password
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. In this example, we will learn about the Spring MVC Passw
8 min read
Spring - MVC Form Text Field
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. In this example, we will learn about the Spring MVC form
8 min read
Spring - MVC Hidden Field
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. In this example, we will learn about the Spring MVC form
6 min read
Spring MVC - Number Validation
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 dispatches requests to handlers, with configurable h
9 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 dispatches requests to handlers, with configurable h
7 min read
Spring - MVC RequestParam Annotation
@RequestParam annotation enables spring to extract input data that may be passed as a query, form data, or any arbitrary custom data. Here, we will see how we can use @RequestParam when building RESTful APIs for a web-based application. Context of the Application: Let us suppose we are implementing a sample feature for the 'Geeksforgeeks' web appli
5 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 Integration: Reusability: A single component, such as the he
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 package, create the Java classes Registration and R
3 min read
three90RightbarBannerImg