是否可以编写自定义 JSP 标记来获取 i18n 消息键并输出给定请求的翻译短语?
通常在 JSP/JSTL 中,我这样做:
<fmt:message key="${messageKey}"><fmt:param>arg1</fmt:param></fmt:message>
我得到了翻译短语。现在我需要执行以下操作(这是有充分理由的):
<custom:translate key="${messageKey}" arg="arg1"/>
但我不知道如何在自定义标签代码中查找翻译。 TagSupport 基类提供了一个 pageContext,我可以从中获取具有 Locale 的 ServletRequest...但是如何查找键的翻译呢?
我使用 Spring 3.0,在 application-context.xml 中,我定义了一个 ReloadableBundleMessageSource,这样我就可以调用:
messageSource.getMessage(
key, new Object[] {arg}, pageContext.getRequest().getLocale()
);
但我不认为我可以将 messageSource 注入自定义标签,可以吗?否则我可以实例化一个新的翻译,但每次调用都会加载数以万计的翻译吗?我不想让 messageSource 成为静态类的静态成员。
我不使用 Spring,但是在“普通”JSP 中,您可以将ResourceBundle
在会话范围内的实例的帮助下Filter
or Servlet
ResourceBundle bundle = ResourceBundle.getBundle(basename, request.getLocale());
request.getSession().setAttribute("bundle", bundle);
在 JSP 中像对待 EL 中的任何其他 bean 一样对待它。
${bundle[messageKey]}
Spring 必须可以将其作为 bean 放入会话范围内。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)