Search code examples
spring-mvcspring-tld

Render Spring Form Select tag from properties file


I am replacing Struts with Spring MVC in my application. Previously, the application uses .properties files to store the label information and is rendered in the JSP pages using Strut tags according to the locale.

The label (data) in properties is like

0000=abc
0001=def

With form:select spring tag, I want to render a dropdown menu which has option with label text of the value from the properties file and value of the key from the properties file.

So far I have been able to render a select tag with all the keys using items attribute of form:select tag but no the desired result.

Also, can the spring tags read and iterate directly from the static .properties files? Right now, I am reading those .properties files in the controller and then passing the list of keys to the view.


Solution

  • I ended up finding a solution. One can fetch the resource bundle in the Controller and pass the list of keys to the view. In the view, JSTL forEach tag can be used to iterate over the list items and pass the key to spring:message tag so that it can read the .properties files for labels

    Something like:

    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    
    <form:select path="fieldToSubmitTheValueTo" multiple="false">
                            <form:option value="-1">
                                <spring:message code="label.select"/>
                            </form:option>
                            <c:forEach items="${labelKeys}" var="key">
                                <form:option value="${key}">
                                    <spring:message code="${key}"/>
                                </form:option>
                            </c:forEach>
                        </form:select>