i18n translation in JSP custom tag

走远了吗. 提交于 2019-12-06 04:36:32

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);

And treat it in JSP like any other bean in EL.

${bundle[messageKey]}

It must be possible to have Spring to put that as a bean in the session scope.

Kristiaan

There is a utility in spring to access the web application context. Then you can look up a bean by its name or type. To get hold of your resource bundle, you could do something like:

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

This question is very old but I think it is worth to share another way to solve this.

To access the Spring message source in a custom tag you only need to extend the class org.springframework.web.servlet.tags.RequestContextAwareTag instead of TagSupport.

In this case you have to implement the method doStartTagInternal() instead of doStartTag(), but inside this method you will have access to the MessageSource through getRequestContext().getMessageSource() method.

Therefore, your class would look like:

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());
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!