是否有速记 ?

是否有速记 ?,第1张

是否有速记

感觉有点像hack,但是您可以编写一个自定义实现,

java.util.Map
该实现在
get(key)
被调用时会从Spring获取消息
MessageSource
。这
Map
可以在下方添加到模型中
msg
的关键,让您使用解引用消息
${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" />

然后

${var}
用作常规EL。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5442012.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存