Retrieve JavaBean names associated with JSP or build variable with dynamic name
-
26-09-2019 - |
문제
I am usign a JavaBean in a jsp page. I would like to give it a dynamic name, because depending on the value of a variable (let's call it foo
), I want it to have different contents, and I want to keep all of these different versions in memory. I want the beans to have session scope, because reevaluating the contents is expensive.
Right now the bean has a static name, and if I reload the page with a different value of foo
, the contents of the bean are the same as before (jsp:usebean
looks for a JavaBean with the specified name, and if it exists, it uses the old one). I would like to keep both the old version and the new, so they have to have different names.
What I want to do is this:
<jsp:useBean id="stats<%=foo%>" class="foo.bar" scope="session">
</jsp:useBean>
My problem is that I cannot reference the JavaBean in JSP code, as I don't know its name. Any ideas on how to solve this?
In essence I want to build a variable with a dynamic name, based on the vaslue of another variable.
Alternatively, I want to retrieve the names of the JavaBeans associated with the current page, so that I obtain a reference to the JavaBean just created.
해결책
Easiest way would be to implement a custom Map
which you store in the session scope. With a Map
you can use the brace notation to dynamically refer a key.
<jsp:useBean id="beanMap" class="com.example.BeanMap" scope="session" />
...
${beanMap[someDynamicKey].someProperty}
You only need to override the Map#get()
method to let it instantiate the bean if absent instead of returning null
.
public class BeanMap extends HashMap<String, Bean> {
@Override public Bean get(Object key) {
Bean bean = super.get(key);
if (bean == null) {
bean = new Bean();
super.put(String.valueOf(key), bean);
}
return bean;
}
}