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
%>
My way is :
Put some this import in your jsp :
Then call the 'getMessage()' static method from 'Resources' class as follows :
Note : do not forget the '=' while inserting the text => 'value="<%=...%>'
First, I would recommend looking at your Action / JSP / Taglibs and see if you absolutely need to use scriptlet code in your JSP. The whole reason for using Struts is to keep a clean MVC model, and avoid business logic leaking into your views (i.e. JSPs).
I would recommend looking into refactoring your scriptlet code:
into directly into your Action class or a reusable service method.
However, if you determine that you absolutely must drop scriptlet code into your JSPs.
< bean:message>
uses the tagclass oforg.apache.struts.taglib.bean.MessageTag
.I looked into the source for this class, and it in turn uses Struts
TagUtils.retrieveMessageResources
, which returns Struts MessageResources:org.apache.struts.util.MessageResources
You could look at mimicking / adapting this code in a more general context than supporting the Struts Taglibs.
Again, though, I would strongly advocate looking into avoiding business logic in scriptlet code whenever possible.
I think this is one way to do it.
Inside struts-config.xml, if you have the following:
Then you do the following:
At the top of the JSP:
Somewhere in the JSP:
Here is a bit cleaner way for use in Java code snippets, based on Gauthier's suggestion.
Import (no change here):
Code snippet:
Hope it will make things cleaner.