• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring MVC Dropdown Box Example

December 17, 2014 by javainterviewpoint Leave a Comment

In this example, we will learn how to create a dropdown box in Spring MVC using Springs tag library. We will use the <form:select> and <form:options> for creating a drop-down. Here we will create a simple Spring MVC form with a country dropdown and we will add validation support to check if it is not empty.

In Spring MVC we will use <form:select> and <form:options> tag to render a dropdown

 <form:select path="country">
     <form:option value="" label="...." />
     <form:options items="${countryList}"/>
 </form:select>

Which produces the below HTML code.

 <select id="country" name="country">
     <option value="">....</option>
     <option value="India">India</option>
     <option value="Australia">Australia</option>
     <option value="England">England</option>
 </select>

Folder Structure :

  1. Create a Dynamic Web Project SpringMVCFormHandling and create a package for our src files “com.javainterviewpoint“
  2. Place the Spring 3 jar files under WEB-INF/Lib 

    commons-logging-1.1.1.jar
    log4j-1.2.16.jar
    slf4j-api-1.7.5.jar
    slf4j-log4j12-1.7.5.jar
    hibernate-validator-4.2.0.Final.jar
    spring-aspects-3.2.4.RELEASE.jar
    spring-beans-3.2.4.RELEASE.jar
    spring-context-3.2.4.RELEASE.jar
    spring-core-3.2.4.RELEASE.jar
    spring-expression-3.2.4.RELEASE.jar
    spring-web-3.2.4.RELEASE.jar
    spring-webmvc-3.2.4.RELEASE.jar
    validation-api-1.1.0.Final.jar
    jstl-1.1.2.jar

  3. Create the Java classes MVC_Controller.java and RegistrationBean.java under com.javainterviewpoint folder.
  4. Place the SpringConfig-servlet.xml and web.xml  under the WEB-INF directory
  5. View files SpringMVC_DropDownExample.jsp and dropdown_Success.jsp are put under the sub directory under WEB-INF/Jsp

Controller

Dropdown_Controller.java

  • The DispatcherServlet mapping which we make in the web.xml will delegate the all the request to our Dropdown_Controller as we have annotated it with @Controller annotation.
  • We use the @RequestMapping annotation to map each of the requests which we get to individual methods. Our controller has three methods getCountry(),initializeForm() and  processForm(). 
  • The getCountry() method returns a list of country which will be used by view for populating the country dropdown.
  • The initializeForm() will take the user to the “SpringMVC_DropdownExample” which is our view component with form backing object DropdownBean.
  •  The processForm() method will get called when the user submits the form. The DropdownBean object “db”  will be validated as we have annotated it with @Valid annotation and the validation results will be added to the BindingResult. Based on the result we will re-direct the user back to the “SpringMVC_DropdownExample” or “dropdown_Success” page.
package com.javainterviewpoint;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class Dropdown_Controller 
{
	ModelAndView mav = null;
	@ModelAttribute("countryList")
	public List getCountry()
	{
		List countryList = new ArrayList();
		countryList.add("India");
		countryList.add("Australia");
		countryList.add("England");
		return countryList;
	}
	
	@RequestMapping("/DropdownExample")
	public String dispForm(Map model)
	{
		DropdownBean db = new DropdownBean();
		model.put("db",db);
		return "SpringMVC_DropdownExample";
		
	}
	@RequestMapping("/processCountry")
	public String processForm(@Valid @ModelAttribute("db") DropdownBean db1,BindingResult result)
	{
		if(result.hasErrors())
		{
			System.out.println("Validation Failed");
			return "SpringMVC_DropdownExample";
		}
		else
		{
			System.out.println("Validated Successfully");
			return "dropdown_Success";
		}
	}
}

Model

DropdownBean.java

Here DropdownBean act as a Model which has a country property. We have added the annotation @NotEmpty to validate if the user has selected a value in the dropdown. The custom validation messages are added in the props.properties file.

package com.javainterviewpoint;


import org.hibernate.validator.constraints.NotEmpty;

public class DropdownBean 
{
	@NotEmpty
	String country;

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}
	
}

View

SpringMVC_DropdownExample.jsp

Our view component has a dropdown field generated using the Spring form tag library. The dropdown gets its value from our controller class. @ModelAttribute(“countryList”) of our controller will be called and it will return a list of Country when <form:options items=”${countryList}”/>  is called.<form:errors> tag displays the error message which occurs during the validation

<%@ 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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
.error {
 color: #ff0000;
}
 
.commonerrorblock {
 color: #000;
 background-color: #ffEEEE;
 border: 3px solid #ff0000;
 
}
</style>
</head>
<body>
 <form:form method="post" action="processCountry" commandName="db">
 <form:errors path="*" element="div" cssClass="commonerrorblock"/>
 <table>
 <tr>
 <td>Country</td>
 <td>
 <form:select path="country">
 <form:option value="" label="...." />
 <form:options items="${countryList}"/>
 </form:select>
 </td>
 <td>
 <form:errors path="country" cssClass="error"/>
 </td>
 </tr>
 <tr>
 <td></td><td><input type="submit"></td>
 </tr>
 </table>
 </form:form>
</body>
</html>

props.properties

NotEmpty.db.country = Please select a Country!!

dropdown_Success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 Country Selected : ${db.country}
</body>
</html>

Configurations

web.xml

The web.xml has everything about the application that a server needs to know, which is placed under the WEB-INF directory. <servlet-name> contains the name of the SpringConfiguration, when the DispatcherServlet is initialized the framework will try to load a configuration file “[servlet-name]-servlet.xml” under the WEB-INF directory.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>SpringMVCFormHandling</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>SpringConfig</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>SpringConfig</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

SpringConfig-servlet.xml

  • The SpringConfig-servlet.xml is also placed under the WEB-INF directory.
  • <context:component-scan> will let the Spring Container to search for all the annotation under the package “com.javainteriviewpoint”. 
  • <mvc:annotation-driven/> annotation will activate the @Controller, @RequestMapping, @Valid etc annotations.
  • The view is resolved through “org.springframework.web.servlet.view.InternalResourceViewResolver” which searches for the jsp files under the /WEB-INF/Jsp/ directory.
  • Resource Bundle is accessed through the “org.springframework.context.support.ResourceBundleMessageSource”  through its property “basename” which has the value “props”, and hence our property file should “props.properties”
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation=" http://www.springframework.org/schema/beans	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 	http://www.springframework.org/schema/context	http://www.springframework.org/schema/context/spring-context-3.0.xsd
 	http://www.springframework.org/schema/mvc	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<context:component-scan base-package="com.javainterviewpoint" />
	<mvc:annotation-driven />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/Jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="props"></property>
	</bean>
</beans>

Lets run our application

Now lets run our application, do a clean build and deploy the application in the Server

Hit on the url “http://localhost:8080/SpringMVCFormHandling/DropdownExample”

SpringMVC_DropdownExample

Submit the form without selecting a value in the dropdown.

SpringMVC_DropdownExample_Validation

Upon successful validation, success page will be returned

SpringMVC_DropdownExample_Success

Other interesting articles which you may like …

  • Spring 3 MVC Hello World Example
  • Spring MVC Form Handling Example
  • Spring MVC Form Validation Tutorial (With Annotations)
  • Spring MVC Form Validation -Annotations and ResourceBundle
  • Spring MVC Exception Handling @ExceptionHandler
  • Spring MVC Exception Handling @ControllerAdvice and @ExceptionHandler
  • Spring MVC Custom Exception Handling
  • Spring MVC Textbox Example
  • Spring MVC Checkbox And Checkboxes Example
  • Spring MVC Radiobutton And Radiobuttons Example
  • Spring MVC TextArea Example
  • Spring MVC HiddenValue Example

Filed Under: J2EE, Java, Spring, Spring MVC, Spring Tutorial Tagged With: Dropdown, Dropdown Box Example, SelectBox, Spring form tag library, Spring MVC, Spring MVC From

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·