写下这样的事情是很乏味和丑陋的:
<input type="button" value="<fmt:message key="submitKey" />" />
Run Code Online (Sandbox Code Playgroud)
如果您想将消息标记嵌套在另一个标记的属性中,则会变得更糟.
有没有任何简写.例如(在JSF中):
<h:commandButton value="#{msg.shareKey}" />
Run Code Online (Sandbox Code Playgroud)
(适用于spring-mvc的解决方案)
ska*_*man 12
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认可的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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
作为备选:
<fmt:message key="key.name" var="var" />
Run Code Online (Sandbox Code Playgroud)
然后${var}用作常规EL.
| 归档时间: |
|
| 查看次数: |
9463 次 |
| 最近记录: |