2

How Can I Internationalize Strings located in Javascript File while Building a Spring MVC WebApp ?

I'm using <spring:message code="label1" /> to Internationalize some static Strings In the JSP Files, but what about error messages located in my js files for example? is there a way to resolve internationalization without including the plain js code in the jsp file ?

I thought about creating a list of values, one for each error, and proceed with ajax calls whenever the page is refreshed, so I can get the right message according the value of the lang variable, but is it wise to do so ?!

TheByeByeMan
  • 1,396
  • 2
  • 28
  • 50

1 Answers1

2

Include this piece of code in some common jsp , say header.jsp.

<script type="text/javascript">
function getSystemLocale() {
    var systemLocale ='<%=RequestContextUtils.getLocale(request)%>';
    return systemLocale;
}

function getResource(){
    jQuery.i18n.properties({
        name:'JS_Messages', 
        path: getContextPath()+'/resource-bundles/JS_Messages/', 
        mode:'both', 
        language:getSystemLocale(),
        callback: function() {
            jQuery.i18n.prop('error_message');
        }
    });
}
</script>

Structure will something as below. It will load all the properties files from the given path and search for the variable based on locale.

Remember the naming convention of file , ending with locale.

Need to include jquery.i18n.properties-min-1.0.9 for the same.

and simply in javascript you can access the key as alert(error_occured);

enter image description here

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116