代码之家  ›  专栏  ›  技术社区  ›  at.

JSP自定义标记中的i18n翻译

  •  3
  • at.  · 技术社区  · 14 年前

    是否可以编写一个定制的JSP标记来获取i18n消息键并输出给定请求的翻译短语?

    通常在JSP/JSTL中,我会:

    <fmt:message key="${messageKey}"><fmt:param>arg1</fmt:param></fmt:message>
    

    我得到了翻译短语。现在我需要做以下工作(这是有充分理由的):

    <custom:translate key="${messageKey}" arg="arg1"/>
    

    但我不知道如何在自定义标记代码中查找翻译。TagSupport基类提供了一个pageContext,我可以从中获取具有区域设置的ServletRequest。。。但是我怎么才能找到翻译的钥匙呢?

    我在我的应用程序中使用Spring3.0-上下文.xml,我定义了一个ReloadableBundleMessageSource,以便调用:

    messageSource.getMessage(
        key, new Object[] {arg}, pageContext.getRequest().getLocale()
    );
    

    3 回复  |  直到 14 年前
        1
  •  2
  •   BalusC    14 年前

    ResourceBundle 会话作用域中的实例 Filter Servlet

    ResourceBundle bundle = ResourceBundle.getBundle(basename, request.getLocale());
    request.getSession().setAttribute("bundle", bundle);
    

    ${bundle[messageKey]}
    

    必须有可能让Spring将其作为bean放入会话范围。

        2
  •  1
  •   Tim Cooper    14 年前

    spring中有一个实用程序可以访问web应用程序上下文。然后您可以根据bean的名称或类型来查找它。 要获得资源包,可以执行以下操作:

    WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
    messageResource = springContext.getBean("messageResource");
    
        3
  •  0
  •   Antonio Lopez    9 年前

    这个问题由来已久,但我认为值得分享解决这个问题的另一种方法。

    org.springframework.web.servlet.tags.RequestContextAwareTag 而不是标记支持。

    在这种情况下,您必须实现方法doStartTagInternal(),而不是doStartTag(),但是在这个方法中,您可以通过getRequestContext().getMessageSource()方法访问MessageSource。

    因此,你的班级看起来像:

    public class CreateCustomFieldTag extends RequestContextAwareTag{
       //variables (key, arg...), getters and setters
       @Override
       protected int doStartTagInternal() throws Exception {
          getRequestContext().getMessageSource().getMessage(
              key, new Object[] {arg}, getRequestContext().getLocale());
       }
    }