admin管理员组

文章数量:1391943

I use this for different languages on our site:

Locale locale2 = (Locale)session.getAttribute("org.apache.struts.action.LOCALE");
ResourceBundle bundle = ResourceBundle.getBundle("content.test.Language", locale2);

I can easy access the string values of the ResourceBundle in HTML to include it on the site via:

<%= bundle.getString("line1") %>

But in some cases I need to access the string values out of javascript. I have not found a way to do this so far.

I only found a ugly workaround to get the string values.

On the HTML part I include:

<input type="hidden" name="hiddenLine2" id="hiddenLine2" value=<%= bundle.getString("line2") %>>

I do this for all strings I could possibly need. To access one of them out of javascript I do this:

var line2 = document.getElementById("hiddenLine2").value;

This is working so far, but I don´t like it.

I am sure there could be a better solution.

I use this for different languages on our site:

Locale locale2 = (Locale)session.getAttribute("org.apache.struts.action.LOCALE");
ResourceBundle bundle = ResourceBundle.getBundle("content.test.Language", locale2);

I can easy access the string values of the ResourceBundle in HTML to include it on the site via:

<%= bundle.getString("line1") %>

But in some cases I need to access the string values out of javascript. I have not found a way to do this so far.

I only found a ugly workaround to get the string values.

On the HTML part I include:

<input type="hidden" name="hiddenLine2" id="hiddenLine2" value=<%= bundle.getString("line2") %>>

I do this for all strings I could possibly need. To access one of them out of javascript I do this:

var line2 = document.getElementById("hiddenLine2").value;

This is working so far, but I don´t like it.

I am sure there could be a better solution.

Share Improve this question asked Feb 18, 2016 at 7:54 MaiLoMaiLo 871 silver badge9 bronze badges 1
  • 1 Javascript runs on the client, Java runs on the server. If you need access to the bundle contents on the client you have to embed them into the HTML generated and sent to the client where Javascript can use them. – Jim Garrison Commented Feb 18, 2016 at 8:08
Add a ment  | 

4 Answers 4

Reset to default 1

Some of the possible solutions.

  1. Use an ajax method to get your resource by passing a key.
  2. Use Hidden input fields and load values.
  3. Use a dedicated jsp page to declare js variables or even a js function to get values according to key.

    like this.

<script type="text/javascript">

    var messageOne = '<%=bundle.getString("line1") %>';
    var messageTwo = '<%=bundle.getString("line2") %>';

</script>

It is normally bad practice to use scriplets <% %> inside your jsp files.

You can use the fmt tag from the jstl core library to fetch information from your resource bundles.

<fmt:bundle basename="bundle">
    <fmt:message var="variableName" key="bundleKey" />
</fmt:bundle>

<input type="hidden" name="hiddenLine2" id="hiddenLine2" value="${variableName}">

should work

infact, i think you can also directly embed it into the javascript with EL aswell

var line2 = ${variableName}; //instead of getting it from document.getElement(...)

Based on what I have tried, you can use jstl library to print the translated messages directly into JavaScript like:

alert("<fmt:message key='line1'/>");

And if you are using struts2 for handling the locales you can easily define you Bundles getting either the struts2 locale, saved by the i18nInterceptor present on the default stack, or the user request locale (the clients' browser one)

<!-- //Import the requierd libraries -->
<%@taglib prefix="fmt" uri="http://java.sun./jsp/jstl/fmt" %>
<%@taglib prefix="c" uri="http://java.sun./jsp/jstl/core" %>

<!-- //Take the Locale from struts if it's present and from the user request if not -->
<c:set var="locale" value="${not empty sessionScope.WW_TRANS_I18N_LOCALE 
? sessionScope.WW_TRANS_I18N_LOCALE : pageContext.request.locale}"/>

<!-- //Get the bundle based on the Locale -->
<fmt:setLocale value="${locale}"/>
<fmt:setBundle basename="content.test.Language"/>

But if you want to be able to extract that JavaScript code into an external .js file on the future I remend you to use some of the internalionalization libraries available for JavaScript, like Globalize (It's the only one I have used, but there are plenty on the net).

The downside of using an external JavaScript library for internationalization is that you will have to define the tranlation resources directly on .js files, it's impossible to access to your .properties on the server from a client-based language like JavaScript.

Here is a different solution.

  1. Load bundle like OP did, with the method getBundle().
  2. Using the third option on Arun's answer, create a separate JSP file to create a custom JavaScript object.

This is the content of said JSP:

<%@page import=".tenea.intranet.conf.Conf" %>
<%@page import="java.util.ResourceBundle,
                java.util.Enumeration" %>

<script type="text/javascript">
    var _get = function(ID){
        if (this.hasOwnProperty(ID))    return this[ID];
        else {
            console.warn("[Resources] Error al obtener clave <"+ ID +">");
            return "[ERROR]";
        }
    };
    var _search = function(text){
        var elems = { }
        Object.keys(this).map(e => {
            if (typeof (this[e]) !== "function" && this[e].includes(text)) { elems[e] = this[e]; }
        });
        return elems;
    };

    var Resources = {
        <% 
            ResourceBundle labels = ResourceBundle.getBundle("content.test.Language", locale2);
            Enumeration<String> e = labels.getKeys();
            while (e.hasMoreElements()) {
                String param = e.nextElement();

                out.print(param +":\""+ labels.getString(param) +"\"");
                if (e.hasMoreElements())    out.println(",");
            }
        %>
    };
    Resources._get = _get;
    Resources._search = _search;

</script>

What this JSP does is:

  • Creates object Resources
  • Using some snippets (sorry Martin :p), and iterating on the list of keys from the resourceBundle, for each key I print a line like "key: value" with out.println().

The resulting object is something like this:

Resources {
    abrilAbrText: "Apr"
    abrilText: "April"
    ...
}

To make some extra functionality, I also added 2 functions inside Resources.

_get() returns the text related to the key passed as parameter. If said key doesn't exist, return the text '[ERROR]'.

_search() is a function I added for development purposes. It searches and returns a custom object with every key whose corresponding text contains the text passed as parameter. NOTE: since it uses "e => {}", it won't work on IE or Safari, so it's best to ment it once the development phase has ended.

Once you have this JSP created, to use it you just have to import it to any JSP you want with this:

<%@include file="[relative_path]" %>

Hope it helps! :)

本文标签: javaGet String out of ResourceBundle in javascript and HTMLStack Overflow