JSP定制标记中的i18n翻译 [英] i18n translation in JSP custom tag
问题描述
是否可以编写自定义JSP标记以获取i18n消息密钥并输出给定请求的翻译短语?
Is it possible to write a custom JSP tag to take an i18n message key and output the translation phrase for the given request?
通常在JSP/JSTL中,我会这样做:
Normally in JSP/JSTL, I do:
<fmt:message key="${messageKey}"><fmt:param>arg1</fmt:param></fmt:message>
然后我得到了翻译短语.现在,我需要执行以下操作(这样做有充分的理由):
And I get the translation phrase. Now I need to do the following (there's a good reason for this):
<custom:translate key="${messageKey}" arg="arg1"/>
但是我不知道如何在自定义标记代码中查找翻译. TagSupport基类提供了一个pageContext,从中可以获取一个具有Locale的ServletRequest……但是我该如何查找密钥的翻译?
But I don't know how to look up the translation in the custom tag code. The TagSupport base class provides a pageContext from which I can get a ServletRequest which has the Locale... but how do I then look up the translation for a key?
我使用Spring 3.0,并在我的application-context.xml中定义了ReloadableBundleMessageSource,因此可以调用:
I use Spring 3.0 and in my application-context.xml, I've defined a ReloadableBundleMessageSource so I can call:
messageSource.getMessage(
key, new Object[] {arg}, pageContext.getRequest().getLocale()
);
但是我不认为我可以将messageSource注入到自定义标签中,可以吗?否则,我可以实例化一个新的实例,但是它会为每个调用加载成千上万的译文吗?我不想求助于使messageSource成为静态类的静态成员.
but I don't think I can inject messageSource into a custom tag, can I? Otherwise I can instantiate a new one, but would it load my tens of thousands of translations for every call? I don't want to resort to making messageSource a static member of a static class.
推荐答案
我不使用Spring,但是在普通" JSP中,您可以在Filter
的帮助下将ResourceBundle
实例放入会话范围或Servlet
I don't do Spring, but in "plain" JSP you can just put the ResourceBundle
instance in the session scope with help of a Filter
or Servlet
ResourceBundle bundle = ResourceBundle.getBundle(basename, request.getLocale());
request.getSession().setAttribute("bundle", bundle);
在JSP中将其像EL中的其他bean一样对待.
And treat it in JSP like any other bean in EL.
${bundle[messageKey]}
必须有Spring才能将其作为bean放入会话范围.
It must be possible to have Spring to put that as a bean in the session scope.
这篇关于JSP定制标记中的i18n翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!