Birds and Bytes

THE EXPERIENCES OF AN AVID BIRDWATCHER AND A SOFTWARE CAVEMAN

0 notes

Sharing Spring MVC localization with the client side

Spring MVC provides a really nice and clean feature set around localization.

I wanted to use the same set of features for the JavaScript side as well, such that if I have:

alert(“Don’t do that!!”)

I can do something that will be easier to localize with:

alert(localeManager[“message.dont_do”]);

There does not seem to be a clean way of doing it, as far as I know.

My implementation is based on extending ResourceBundleMessageSource, as suggest in: http://stackoverflow.com/questions/6915312/spring-get-all-resolvable-message-keys

So I have:

package org.springframework.context.support;

import java.util.Locale;

import java.util.ResourceBundle;

import java.util.Set;

public class ExposedResourceBundleMessageSource extends

        ResourceBundleMessageSource {

    public Set<String> getKeys(String basename, Locale locale) {

        ResourceBundle bundle = getResourceBundle(basename, locale);

        return bundle.keySet();

    }

}

I than created the following Controller that takes advantage of the Jackson power:

@RequestMapping(value = “/resourceBundle.htm”)

public  ModelAndView welcomePage(HttpServletRequest request, Locale  locale) throws IOException {

ModelAndView mav = new ModelAndView();

Set<String> keys = ((ExposedResourceBundleMessageSource)

 messageSource).getKeys(“messages”, locale);

Map<String, String> pairs = new HashMap<String, String>();

for (String key : keys){

pairs.put(key, messageSource.getMessage(key, null, locale));

}

ObjectMapper mapper = new ObjectMapper();

mav.setViewName(“resources”);

mav.addObject(“entriesAsJson”, mapper.writeValueAsString(pairs));

return mav;

}

The very simple View (above “resources”);

labelManager = ${entriesAsJson};

And that’s all !

Using it, In my JSPs/HTMLs, I can now call:

<script src=”./resourceBundle.htm”></script>

And when I want to use the label, as planned, I simply call, in my Javascript files:

alert(localeManager[“message.dont_do”]);


I’d be very happy to hear of other solutions to the problem of localization in JavaScript files.