Search code examples
javajspstruts

bean:message equivalent in java code?


I'm using Struts 1.2 and I need to reference the value of some internationalized strings in a JSP page. Normally I would do this using the < bean:message > tag, but I need to reference it from the Java code (surrounded by <% ... %>) instead.

How can I do this?

For example:

<% 
person.setName("John Smith");
person.setOccupation("Chef");   // I want to internationalize this string
%>

Solution

  • I think this is one way to do it.

    Inside struts-config.xml, if you have the following:

    <message-resources parameter="ABC"/>
    

    Then you do the following:

    At the top of the JSP:

    <%@ page import="java.util.Locale" %>
    <%@ page import="org.apache.struts.Globals" %>
    <%@ page import="org.apache.struts.util.MessageResources" %>
    

    Somewhere in the JSP:

    <%    
    MessageResources mr = MessageResources.getMessageResources("ABC");
    Locale locale = (Locale) session.getAttribute(Globals.LOCALE_KEY);
    
    person.setName("John Smith");
    person.setOccupation(mr.getMessage(locale, "Chef"));
    %>