On Wed, Jul 15, 2009 at 23:33, Frank van der Kleij <[email protected]>wrote:
>
> Has anyone used the ServerSession attributes? I'm puzzled by the
> AttributeKey class that is used to define the key. It's an empty class
> without any state. The only way I can see to use it is to make a subclass of
> it, but that seems like a lot of trouble just to store something in the
> session.
> To be useful it should have some state together with the methods hashCode
> and equals. The subclass I made is based on a String...
> Am I missing something or should everyone define his own key? It would be
> nice if something workable would be in the core...
Yes, its easier than that. All you have to do is this:
class MyState {
public static final AttributeKey<MyState> MY_STATE = new
AttributeKey<MyState>();
public static MyState get(ServerSession s) {
return s.getAttribute(MY_STATE);
}
public void put(ServerSession s) {
s.setAttribute(MY_STATE, this);
}
}
No need to subclass it. The reason AttributeKey exists as it does is to
make the get/set methods have type safe signatures. You just need to create
a new instance of the AttributeKey to get a unique entry in the attribute
map. Since AttributeKey is then relying on reference equality, two keys are
only equal if they are the same key instance. You can scope your attribute
data by scoping your AttributeKey instance; if nobody can get your key,
nobody can get (or set) your attribute.