Translation of i18n into a custom JSP tag

Can I write my own JSP tag to take the i18n message key and display the translation phrase for this request?

Usually 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 is a good reason for this):

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

But I do not know how to search for a translation in the code of a user tag. The TagSupport base class provides a pageContext from which I can get a ServletRequest that has a Locale ... but how can I look for a translation for a key?

I use Spring 3.0 and in my application-context.xml, I defined the source ReloadableBundleMessageSource, so I can call:

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

, messageSource , ? , ? , messageSource .

+3
3

Spring, "" JSP ResourceBundle Filter Servlet

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

JSP, bean EL.

${bundle[messageKey]}

, Spring bean .

+2

spring -. bean . , - :

WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
messageResource = springContext.getBean("messageResource");
+1

, , .

Spring , org.springframework.web.servlet.tags.RequestContextAwareTag TagSupport.

doStartTagInternal() doStartTag(), MessageSource getRequestContext(). getMessageSource().

, :

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());
   }
}
0

Source: https://habr.com/ru/post/1764811/


All Articles