views:

28

answers:

1

How do I use jsp:useBean with collections like Lists and Maps correctly?

I can get Lists by using

    type="List<MyObject>"

but I cannot get the List to instantiate if nothing is passed.

    class="ArrayList<MyObject>"

And the above attribute gives an error:

The value for the useBean class attribute ArrayList`<MyObject`> is invalid.

And both the attributes fail for a HashMap.

Currently, I'm reading the objects using getAttribute() but it'll be cleaner to use the tags and set them up.

+1  A: 

Have you tried just

class="java.util.ArrayList"

Remember, the actual type name doesn't include the generic type, that's syntactic sugar used within the Java language itself, and <jsp:useBean> isn't part of the Java language.

skaffman
I guess my phrasing was unclear. I've edited my post a bit. The class attribute is the one throwing the error. The type attribute works for lists, but doesn't instantiate the list if null is passesd.
manu1001
@manu101: Yes, but `class="ArrayList<MyObject>"` is not valid, because `ArrayList<MyObject>` is not a valid type. The type is `java.util.ArrayList`
skaffman
@manu1001, skaffman is entirely right. I just wanted to add, the `jsp:useBean` is superfluous if you don't need to set items in the list (for which there's no way using `jsp:` or `c:` tags by the way) and when you are accessing it using pure EL (e.g. `${foo}` and so on). You could leave the `jsp:useBean` line away, unless for pure documentation or IDE-support purposes.
BalusC
Ok, got it. It works for Lists now. But what about HashMap? The same doesn't work. Basically, I want to know how to read a HashMap<MyObject1, MyObject2> from the request scope using the useBean tag.
manu1001
@manu1001: if `java.util.ArrayList` worked, then so will `java.util.HashMap`
skaffman