我有一个 @SessionScoped bean,我想将其用作映射,以便我可以在 View 中使用 EL 动态获取其属性。
myBean['someDynamicProperty']
我通过实现 java.util.Map、使用我的应用程序逻辑实现 get(Object o) 并在所有其他重写的 Map 方法中抛出 UnsupportedOperationException 来实现这一目标。
@SessionScoped
@Named
public class MyBean implements Map<String, String> {
@Override
public String get(Object key) {
// Application logic here
}
@Override
public boolean containsKey(Object key) {
throw new UnsupportedOperationException();
}
// All other map methods overriden like containsKey
}
这些属性是只读的,我只需要使用代码中的 get 方法,但不实现其他 Map 方法是否安全?
是否有更好的方法来定义 bean 中 EL 的动态属性?
最佳答案
最好将 map 存储为 session 属性,这样您就不需要创建 @SessionScoped
bean,并且可以通过表达式语言访问它而不会出现问题。
public void methodThatShouldCreateTheMap() {
//declaring the variable as myBean for compatibility with your current code
Map<String, Object> myBean = new HashMap<String, Object>();
//fill myBean here...
//...
//store myBean in session
FacesContext.getCurrentInstance()
.getExternalContext()
.getSession(false)
.setAttribute("myBean", myBean);
}
您可以直接在 EL 中访问 map :
${myBean['key']}
<小时/>
来自评论:
The issue is that my bean is not really a
Map
. In the get method I implement the logic I require based on the key that I receive. (...) In my case the business logic in the getter is not costly.
似乎在某种程度上您需要 bean 来实现 Map
接口(interface)。相反,重新发明轮子或标记抛出 UnsupportedOperationException
的方法,而是从已实现所有方法的类扩展,例如 HashMap
或 LinkedHashMap
,或者实现 Map
但根本不实现它的类,例如 AbstractMap
,并将其他方法留空:
@Named
@SessionScoped
public class MyBean extends AbstractMap<String, Object> {
@Override
public Object get(String key) {
//add your logic here...
}
@Override
public void set(String key, Object value) {
//do nothing...
}
//similar for other unnecessary methods...
}
关于java - 通过实现 java.util.Map#get 为 EL 提供动态 bean 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23350773/