是否有< fmt:message key =" key"的缩写/&GT ;? [英] Is there a shorthand for <fmt:message key="key" />?

查看:218
本文介绍了是否有< fmt:message key =" key"的缩写/&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

写这样的东西很乏味又难看:

It's tedious and ugly to write things like:

<input type="button" value="<fmt:message key="submitKey" />" />

如果你想将消息标记嵌套在另一个标签的属性中,它会变得更糟。

And in case you want to nest the message tag in another tag's attribute it becomes even worse.

是否有任何简写。例如(如在JSF中):

Is there any shorthand for that. For example (like in JSF):

<h:commandButton value="#{msg.shareKey}" />

(适用于spring-mvc的解决方案)

(spring-mvc-only solutions applicable)

推荐答案

这感觉有点像黑客,但你可以写一个 java.util.Map 的自定义实现,当调用 get(key)时,从Spring MessageSource 中获取消息。可以将 Map 添加到 msg 键下的模型中,允许您使用<$ c $取消引用消息c> $ {msg.myKey} 。

This feels like a bit of a hack, but you could write a custom implementation of java.util.Map which, when get(key) is called, fetches the message from the Spring MessageSource. This Map could be added to the model under the msg key, allowing you to dereference the messages using ${msg.myKey}.

也许有一些其他动态结构比JSP EL识别的不是地图,但我不能想到一个。

Perhaps there's some other dynamic structure than is recognised by JSP EL that isn't a Map, but I can't think of one offhand.

public class I18nShorthandInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = Logger.getLogger(I18nShorthandInterceptor.class);

    @Autowired
    private MessageSource messageSource;

    @Autowired
    private LocaleResolver localeResolver;

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {

        request.setAttribute("msg", new DelegationMap(localeResolver.resolveLocale(request)));

        return true;
    }

    private class DelegationMap extends AbstractMap<String, String> {
        private final Locale locale;

        public DelegationMap(Locale locale) {
            this.locale = locale;
        }

        @Override
        public String get(Object key) {
            try {
                return messageSource.getMessage((String) key, null, locale);
            } catch (NoSuchMessageException ex) {
                logger.warn(ex.getMessage());
                return (String) key;
            }
        }
        @Override
        public Set<Map.Entry<String, String>> entrySet() {
            // no need to implement this
            return null;
        }

    }
}

作为替代方案:

<fmt:message key="key.name" var="var" />

然后使用 $ {var} 作为常规EL。

Then use ${var} as a regular EL.

这篇关于是否有&lt; fmt:message key =&quot; key&quot;的缩写/&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆