I have a web application which uses Spring MVC. I would like to have my interface consist of just a single page which retrieves all data dynamically as JSON via AJAX. My problem is with internationalization. When I render content in jsps, I can use JSTL tags to resolve my keys (super-easy with Spring MVC):
<fmt:message key="name"/>: ${name}
<fmt:message key="title"/>: ${title}
<fmt:message key="group"/>: ${group}
When properly configured, it renders in finnish locale as
Nimi: yay
Otsikko: hoopla
Ryhmä: doo
Now, when I use json, I have only this coming in from the server:
{
name: "yay",
title: "hoopla",
group: "doo"
}
There's no keynames! But I have to provide them somehow. I considered changing the keynames to their localized forms or adding the localized keynames to json output (eg. name_localized="Nimi") but both of these options feel like bad practice. I'm using jackson json to automatically parse my domain objects into json and I like the encapsulation it provides.
The only feasible solution I came up with is this: dynamically create a javascript file with the localized keynames as variables.
<script type="text/javascript">
var name="Nimi";
var title="Otsikko";
var group="Ryhmä";
</script>
Once I have this loaded, I now have all the information in my javascript to handle the json! But there's a gotcha: my list of field names is dynamic. So actually static rendering in jsp would look like this:
<c:forEach var="field" values="${fields}">
<fmt:message key="${field.key}"/>: ${field.value}
</c:forEach>
I need to find all of the messages specified in my messages.properties. Spring MessageSource interface only supports retrieving messages by key. How can I get a list of keynames in my JSP which renders the localized javascript variables?