Spring MVC Form – Drop-Down List

We have already discussed the Spring MVC form tags available in the form tag library. Form tags are used to develop web applications easily. In this tutorial, we are going to discuss the following tags:

<form:select> - It represents the HTML<select> tag, which presents a list of items. It also supports the nested <form:option> and <form:options> tag.

Below is given a code snippet which shows how to use the <form:select> tag:

  <form:select path = "...">
    ...
 </form:select> 

The option tag is always defined inside the select tag.

<form:option> - It represents the HTML option tag, which presents a single option. E.g., one option tag represents a single option of the drop-down list.   

Below is given a code snippet which shows how to use the <form:option> tag:

<form:option value ="…" label = "…"></form:option>

<form:options> - It represents the HTML options tag, which presents a list of option tags. E.g., an options tag contains a list of option tags.

Below is given a code snippet which shows how to use the <form:options> tag:

<form:options items ="…"></form:options>

Let’s understand the concept of <form:select> and <form:option> tags with the help of an example.

Example of MVC Form Drop-down list

Here, we are going to create an example of a drop-drop list. Below are the steps to create an example of a drop-down list:

  • Create a request page

In this step, we are going to create a request page named index.jsp.

index.jsp

 <html>
 <body>
 <h2> Spring MVC Web application </h2>
 <a href = "student_form"> Student Form</a>
 </body>
 </html> 
  • Create the Model class

In this step, we are going to create a Model class named Student.java, which stores the data of the drop-down list.

Student.java

 public class Student {
             private String fname;
             private String lname;
             private String country;
               public Student() {
             }
               public String getCountry() {
                         return country;
             }
             public void setCountry(String country) {
                         this.country = country;
             }
             public String getFname() {
                         return fname;
             }
             public void setFname(String fname) {
                         this.fname = fname;
             }
             public String getLname() {
                         return lname;
             }
             public void setLname(String lname) {
                         this.lname = lname;
             }
  } 
  • Create the Controller class

In this step, we are going to create a Controller named StudentController.java, which returns the JSP pages.

StudentController.java

 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.RequestParam;
 @Controller
 public class StudentController {
                @RequestMapping("/student_form")
             public String showStudentForm( Model m) {
                         Student student = new Student();
                         m.addAttribute("student", student);
                         return "studentform" ;
             }
             @RequestMapping("/studentregis")
             public String showStudentData(@ModelAttribute("student") Student student) {
             return "student-data" ;
             }
  } 
  • Add the entry of Controller in the web.xml

In this step, we are going to add the entry of the Controller inside the web.xml file.

web.xml

 <?xml version = "1.0" encoding = "UTF-8"?>
 <web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
             xmlns = "http://xmlns.jcp.org/xml/ns/javaee"
             xsi:schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             id = "WebApp_ID" version = "3.1">
             <display-name>spring-mvc-demo</display-name>
             <absolute-ordering />
             <!-- Spring MVC Configs -->
             <!-- Step 1: Configure Spring MVC Dispatcher Servlet -->
             <servlet>
                         <servlet-name>dispatcher</servlet-name>
                         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                         <init-param>
                                     <param-name>contextConfigLocation</param-name>
                                     <param-value>/WEB-INF/spring-servlet.xml</param-value>
                         </init-param>
                         <load-on-startup>1</load-on-startup>
             </servlet>
             <!-- Step 2: Set up URL mapping for Spring MVC Dispatcher Servlet -->
             <servlet-mapping>
                         <servlet-name>dispatcher</servlet-name>
                         <url-pattern>/</url-pattern>
             </servlet-mapping>
 </web-app> 
  • Define the Model in another XML file.

In this step, we are going to define the Model in another XML file (spring-servlet.xml).

spring-servlet.xml

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:mvc="http://www.springframework.org/schema/mvc"
             xsi:schemaLocation="  http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context.xsd
             http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 
             <!-- Step 3: Add support for component scanning -->
             <context:component-scan base-package="com.app.SpringMVCFormTag" />
             <!-- Step 4: Add support for conversion, formatting and validation support -->
             <mvc:annotation-driven/>
             <!-- Step 5: Define Spring MVC view resolver -->
             <bean
                         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                         <property name="prefix" value="/WEB-INF/view/" />
                         <property name="suffix" value=".jsp" />
             </bean>
 </beans> 
  • Create all the view pages

In this step, we are going to create all the view pages (JSP page).

studentform.jsp

 <%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %>  
 <html>
 <head>
 <title>Student Registration Form</title>
 </head>
 <body>
 <form:form action = "studentregis" modelAttribute = "student" >
 FIRST NAME: <form:input path = "fname" />
 <br></br>
 LAST NAME: <form:input path = "lname" />
 <br></br>
 <form:select path="country">
    <form:option value = "IND" label = "India"></form:option>
    <form:option value = "FRA" label = "France"></form:option>
    <form:option value = "USA" label = "America"></form:option>
    <form:option value = "DUB" label = "Dubai"></form:option>
    <form:option value = "NEP" label = "Nepal"></form:option>
    <form:option value = "BHU" label = "Bhutan"></form:option>
 </form:select>
 <br></br>
 <input type = "submit" value = "Submit"/>
 </form:form>
 </body>
 </html> 

student-data.jsp

 <%@ page language = "java" contentType = "text/html; charset=ISO-8859-1"
     pageEncoding = "ISO-8859-1"%>
 <!DOCTYPE html>
 <html>
 <head>
 <meta charset = "ISO-8859-1">
 <title>Student Registration Data</title>
 </head>
 <body>
 The student name is ${student.fname} ${student.lname}
 <br></br>
 Country: ${student.country}
 </body>
 </html> 

Output

Spring MVC Form – Drop-Down List
Spring MVC Form – Drop-Down List 1
Spring MVC Form – Drop-Down List 2
Spring MVC Form – Drop-Down List 3

Read the list from a Java Class

In the above example, the web form read the values of the drop-down list from the studentform.jsp page. Now, we are going to create an example of reading the list data from a Java class (Bean).

Here, we are taking the previous example for modifications. The modifications are done in the following classes:

  • Student.java
 import java.util.LinkedHashMap;
 public class Student {
             private String fname;
             private String lname;
             private String country;
             private LinkedHashMap<String, String> countryoptions;
         public Student() {
             countryoptions = new LinkedHashMap<String, String>();
                         countryoptions.put("IND","India");
                         countryoptions.put("FRA","France");
                         countryoptions.put("USA","America");
                         countryoptions.put("DUB","Dubai");
                         countryoptions.put("NEP", "Nepal");
                         countryoptions.put("BHU", "Bhutan");
                         countryoptions.put("UK", "United Kingdom");
             }
             public String getCountry() {
                         return country;
             }
             public LinkedHashMap<String, String> getCountryoptions() {
                         return countryoptions;
             }
             public void setCountry(String country) {
                         this.country = country;
             }
             public String getFname() {
                         return fname;
             }
             public void setFname(String fname) {
                         this.fname = fname;
             }
             public String getLname() {
                         return lname;
             }
             public void setLname(String lname) {
                         this.lname = lname;
             }
  } 

In the above code snippet (Student.java), we have provided the drop-down list values. Now, the web form will read the list from the above Java class.

  • studentform.jsp
 <%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %>  
 <html>
 <head>
 <title>Student Registration Form</title>
 </head>
 <body>
 <form:form action = "studentregis" modelAttribute = "student" >
 FIRST NAME: <form:input path = "fname" />
 <br></br>
 LAST NAME: <form:input path = "lname" />
 <br></br>
 <form:select path="country">
    <form:options items = "${student.countryoptions}"></form:options>
 </form:select>
 <br></br>
 <input type = "submit" value = "Submit"/>
 </form:form>
 </body>
 </html> 

In the above code snippet (studentform.jsp), we have removed the drop-down list values from the above form page.

Output

Spring MVC Form – Drop-Down List 4
Spring MVC Form – Drop-Down List 5
Spring MVC Form – Drop-Down List 6
Spring MVC Form – Drop-Down List 7

In the above example, we have read the drop-down list values from a Java class. Similarly, we can read any data values like checkbox, radio-button, etc., from a Java class.


Related Topics

Spring – Dependency Injection

Spring – Dependency Injection One of the main features of Inversion of Control (IoC) is Dependency Injection (DI). It is a process of supplying the dependencies from one object to others. The Spring-Core container...

8 minutes read.

Spring - Bean Scope

Spring - Bean Scope Bean Scope refers to a lifecycle of the bean. It allows us to have control over the creation of bean objects. It is a very powerful approach and provides...

6 minutes read.

Spring AOP – Pointcut Expressions

Spring AOP – Pointcut Expressions Pointcut refers to a collection of join points that specify where advice to be applied. In other words, pointcut represents a set of various join points. It defines that...

7 minutes read.

Spring - Bean lifecycle using annotations

Spring - Bean lifecycle using annotations We have already discussed the bean lifecycle using an XML-based configuration. In the previous case, we have declared the init-method and destroy-method attributes in the bean-configuration file. Here, we...

2 minutes read.

Spring Autowiring

Spring Autowiring Autowiring is an essential feature of the Spring framework. The autowiring function is used for wiring beans automatically, without injecting the beans using <constructor-arg> and <property> elements in the bean-config file. It can...

3 minutes read.

Spring MVC Regular Expression Validation

Example of Regular Expression Validation Here, we are going to create an example of regular expression validation. Following are the steps to create an example of a regular expression: Create a request page In this step, we are going...

13 minutes read.

Spring Autowiring – Constructor Injection

Spring Autowiring – Constructor Injection We have previously discussed an example of Constructor Dependency Injection (CDI) using an XML-based configuration. In the previous case, we have defined the reference of the constructor in...

2 minutes read.

Spring Tutorial

What is Spring Framework? Spring is one of the most popular enterprise application framework used for developing Java applications. “Spring is a lightweight open-source framework. It allows Java developer to build simple, reliable,...

6 minutes read.

Spring MVC Form – Radio Button

A variety of form tags are available in Spring MVC for developing web applications, <form:radiobutton> tag is one of them. The radio button tag is used to choose only one option among a...

10 minutes read.

Spring - Bean Scopes with Annotations

Spring - Bean Scopes with Annotations We have previously discussed the Spring bean scopes using an XML-based configuration. In the XML-based configuration, we have defined the beans and its scope inside the bean-config...

3 minutes read.

Spring – Beans using @Bean

Spring – Beans using @Bean We have previously discussed an example of Spring configuration using an XML-based configuration. In the previous example, we have defined beans inside the bean-configuration file (applicationContext.xml). To make the...

3 minutes read.

Spring AOP - @AfterThrowing Advice

Spring AOP - @AfterThrowing Advice As we have discussed in our previous tutorial, Advice is one of the essential concepts of the Spring AOP. The after throwing advice is one of the types of...

3 minutes read.

Spring – Bean Lifecycle

Spring – Bean Lifecycle Spring bean is responsible for managing the lifecycle of beans created by the Spring container.  The lifecycle of the bean is easy to understand. When a bean is created, it requires...

4 minutes read.

Spring – Configuration using @Configuration

Spring – Configuration using @Configuration We have previously discussed the Spring configuration using an XML configuration file. In that case, we have defined all the bean information in the bean-configuration file (applicationContext.xml). ...

3 minutes read.

Spring MVC Example

Spring MVC Example We have previously discussed the Spring Web MVC framework. In this tutorial, we are going to create a simple example of Spring Web MVC. Following are the steps used to create an example...

2 minutes read.

Spring Autowiring –Field Injection

Spring Autowiring –Field Injection The Field Injection is used to inject the fields, variables, or properties of the beans. It is not available in autowiring using XML- based configuration. It is a...

2 minutes read.

Spring MVC Form – Drop-Down List

We have already discussed the Spring MVC form tags available in the form tag library. Form tags are used to develop web applications easily. In this tutorial, we are going to discuss the...

13 minutes read.

Spring Framework Annotations

Spring Framework Annotations Spring framework provides a variety of annotations for a better approach. Using annotations, we can develop Spring applications (small & large scale) easily with less code. Following are the annotations...

6 minutes read.

Spring AOP – @After Advice

Spring AOP – @After Advice We have previously discussed the concepts of Spring AOP. One of the AOP concepts is Advice, which is further divided into various types. After (finally) is a type of advice...

3 minutes read.

Spring MVC Form Text Field

We have previously discussed the Spring MVC form tags. The form tag library provides a variety of form tags that are used to build web applications. One of them is a <form:input>...

8 minutes read.