是否有<fmt:message key=“key”/>的简写?
写这样的东西既乏味又丑陋:
<input type="button" value="<fmt:message key="submitKey" />" />
如果您想将消息标记嵌套在另一个标记的属性中,情况会变得更糟。
有没有简写。例如(如在JSF中):
<h:commandButton value="#{msg.shareKey}" />
(适用弹簧-mvc-only解决方案)
写这样的东西既乏味又丑陋:
<input type="button" value="<fmt:message key="submitKey" />" />
如果您想将消息标记嵌套在另一个标记的属性中,情况会变得更糟。
有没有简写。例如(如在JSF中):
<h:commandButton value="#{msg.shareKey}" />
(适用弹簧-mvc-only解决方案)
这感觉有点像黑客攻击,但是您可以编写一个自定义实现,当调用该实现时,从Spring中获取消息 。这可以添加到键下的模型中,允许您使用 取消引用消息。java.util.Mapget(key)MessageSourceMapmsg${msg.myKey}
也许还有其他一些动态结构不是 JSP EL 所识别的,但我想不出一个。Map
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" />
然后用作常规 EL。${var}
如果你想要的只是一个快捷方式,你可以创建一个标签文件,比如btn.tag。
<%@tag%>
<%@ attribute name="key" required="true" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<input type="button" value="<fmt:message key="${key}" />" />
并像这样使用它
<%@ taglib tagdir="/WEB-INF/tags" prefix="tags"%>
...
<tags:btn key="submitKey" >
...