wutzebaer 的答案是正确的,但是当文字的变量有任何点时,它就会出现问题,例如“person.name”
<script type="text/javascript">
var msg = new Object();
<c:forEach items="#{msg.keySet()}" var="key">
try{
//msgTempl.#{key} = "#{msg[key]}";
msg['#{key}'] = "#{msg[key]}"; //works better than msgTempl.#{key} = "#{msg[key]}"; when the key contains dots like 'fields.name'
}catch(e){
console.log("error fullfilling the msgForms resource from bundle " +e);
}
</c:forEach>
</script>
这对我有用,但 netbeans 显示此错误:
Error: The prefix "c" for the "c: forEach" element is not linked.
因为它在脚本中放置了一个 JSTL 标记,但它工作正常,但是
还有另一种方法可以做到这一点
@ManagedBean(name = "ResouceBundle")
@ApplicationScoped
public class ResouceBundle implements Serializable {
private static final long serialVersionUID = 1L; //needed because the bean is application|session|view and it needs to be Serializable
public String msg;
@PostConstruct
public void init() {
this.msg = createResourceBundleJSON("resourceName");
}
public String createResourceBundleJSON(String resourceName) {
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle bundle = context.getApplication().getResourceBundle(context, resourceName);
JSONObject jsonObj = new JSONObject();
Set<String> keys = bundle.keySet();
for (String key : keys) {
jsonObj.put(key, JSONObject.wrap(bundle.getString(key)));
}
return jsonObj.toString();
}
public String getMsg() {
return msg;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
}
然后,在 XHTML 中,只写:
<script type="text/javascript">
var msg = #{ResouceBundle.msg}
</script>