Spring MVC dropdown options load from properties file





Hey guys in this post, you will learn about Spring MVC dropdown options load from properties file

1. Create a Property file


Create WEB-INF/countries.properties file and add the following content

IND=India
BRA=Brazil
AUS=Australia
GER=Germany
SAF=South Africa

2. Add Schema in Spring Config file


Update the spring config file spring-mvc-dispatcherservlet.xml and add the following schemas at the top

<?xml version="1.0" encoding="UTF-8"?>
<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:util="http://www.springframework.org/schema/util" 
        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.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 
            http://www.springframework.org/schema/util     
            http://www.springframework.org/schema/util/spring-util.xsd">

3. Load the property file


Inside the spring config file load the property file by using the <util:properties> tag

<util:properties  id="countryOptions" location="classpath:../countries.properties" />

4. Inject the Property values to Java Map


Inside the controller EmployeeController.java inject the properties value to a Java Map<String, String>

@Value("#{countryOptions}") 
private Map<String, String> countryOptions;

5. Add the Map to Spring Model


Inside the controller EmployeeController.java create a handler method and add the map values to Spring Model

@RequestMapping("/showForm") 
public String showForm(Model theModel) { 
 
    Employee theEmployee = new Employee();
 
    theModel.addAttribute("employee", theEmployee); 
 
    theModel.addAttribute("theCountryOptions", countryOptions); 
 
    return "home-page"; 
}

6. Update view template


Inside the home-page.jsp read the map values from Spring Model and populate it inside the HTML dropdown

<form:select path="country"> 
 <form:options items="${theCountryOptions}" />
</form:select>

Run the App


Start the tomcat server, navigate to the URL localhost:8080/springmvc/
23

24
That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply