所以我的消息文件中有一堆消息,键如下
alt.text1=Hello
alt.text2=Goodbye
在我的 JSP 中,我可以很好地获取和显示这些
<spring:message code="alt.text1"/>
<spring:message code="alt.text2"/>
呈现为
Hello Goodbye
问题是,我如何获取键以"alt"开头的所有消息。IE 我想显示一次所有"alt"消息,但不显示文件中不以 alt 开头的任何其他消息。
我知道这些消息是JSP中的哈希映射,例如,我如何访问此映射以迭代其键和值?
我最终创建了一个如下所示的CustomerMessageSource
,并将listAllAltLabels的结果放在视图上。然后是一个简单的迭代案例。
public class CustomMessageSource extends ReloadableResourceBundleMessageSource {
public Map<String, String> listAllAltLabels(String basename, Locale locale) {
Map<String, String> altLabels = new HashMap<String, String>();
PropertiesHolder propertiesHolder = getMergedProperties(locale);
Properties properties = propertiesHolder.getProperties();
for(Object key : properties.keySet()){
if(((String)key).startsWith("alt.")) {
altLabels.put((String)key, (String)properties.get(key));
}
}
return altLabels;
}
}
我使用 spring webflow(隐藏大多数控制器),但基本上在渲染页面之前在控制器/操作中的某个地方,调用 listAllAltLabels 并将结果分配给"altLabelMessages"并将其放入模型/视图中。
然后在视图中 (jsp)
<c:forEach items="${altLabelMessages}" var="message">
<form:option value="${message.key}" label="${message.value}"/>
</c:forEach>
,但看起来没有标签可以使用 Spring 获取消息包。
如果您使用<fmt:setBundle/>
您将获得一个LocalizationContext
对象,其中包含一个ResourceBundle
。遗憾的是,keySet
方法无法使用表达式语言访问。
您可以做的是将消息包加载到 Bean 中并创建一个以 alt.
开头的键列表,或者只公开整个键集。