bean:message equivalent in java code?

2019-07-18 03:47发布

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
%>

标签: java jsp struts
4条回答
Evening l夕情丶
2楼-- · 2019-07-18 04:23

My way is :

Put some this import in your jsp :

<%@ page import="org.apache.struts.validator.Resources" %>

Then call the 'getMessage()' static method from 'Resources' class as follows :

<sometag name="p1" value="<%=Resources.getMessage(request, \"my.property.from.resources\")%>"/>

Note : do not forget the '=' while inserting the text => 'value="<%=...%>'

查看更多
Ridiculous、
3楼-- · 2019-07-18 04:28

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:

<%  
    person.setName("John Smith"); 
    person.setOccupation("Chef");    
%> 

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 of org.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.

查看更多
放我归山
4楼-- · 2019-07-18 04:33

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"));
%>
查看更多
仙女界的扛把子
5楼-- · 2019-07-18 04:44

Here is a bit cleaner way for use in Java code snippets, based on Gauthier's suggestion.

Import (no change here):

<%@ page import="org.apache.struts.validator.Resources" %>

Code snippet:

<% 
person.setName("John Smith");
person.setOccupation(Resources.getMessage(request, "occupation.property.from.resources"));
%>

Hope it will make things cleaner.

查看更多
登录 后发表回答