views:

100

answers:

1

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.

A: 

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;
    }
}
BalusC
This seems simple enough, and I can also un-Bean the foo.bar class (which I prefer). However, I'd be doing something that the JSP framework has already implemented, which I'd rather not.I guess if I can't do what I originally thought, this is an acceptable hack. :) Thank you for your answer!
FrontierPsycho
I tried to do this, and Java doesn't understand that Bean is a class, it thinks it is a type parameter, even though I imported the class. Thus "new Bean()" gives an error. I even tried it with "String" and I get the same thing.
FrontierPsycho
I used this solution, although modified a bit. I didn't extend HashMap (as it was not possible), but I used a Hashtable in the useBean tag, and I implemented the above logic in my jsp code. Not very clean, but it works and it isn't that ugly.
FrontierPsycho