Friday, 10 March 2017

How to detect changes to Sessions in JavaEE

what is mean by changes to HttpSession?

1. adding attributes to session.
2. removing attributes from session.

These changes can be notified by web container to your application, using listeners. This enables you to decouple the code that needs to be aware of session changes from the code that makes changes to sessions.

one more case is, when third party frameworks, such as Spring or Spring Security make changes to sessions in you application, listeners enables you to detect these changes without changing the third-party code.

You can create listeners, by annotating class with @WebListener.

below or some session interfaces:

1. HttpSessionAttributeListener - for listening to events, when attributes are added, updated or removed.

2. HttpSessionBindingListener -
    Methods in this interface are valueBound() & valueUnBound(). for example, if class Foo implements HttpSessionBindingListener and you add an instance of Foo to an HttpSession using setAttribute, the container calls the instance's valueBound method. Likewise, the container call's the instance's valueUnbound method when you remove it from the session using removeAttribute.

With the help of HttpSessionBindingListener, your attribute can synchronize itself with an underlying database (and update the database when it is removed from a session). 


3. HttpSessionListener
    This interface has 2 methods, namely sessionCreated(), sessionDestroyed(). sessionCreated() is called, whenever a new session is created. sessionDestroyed() is called whenever something causes the session to no longer be valid i.e calling session.invalidate() or can be implicit invalidation due to an inactivity timeout.

The common usecase for this listener is, when administrator want to log this information for some record-keeping purposes.

4. HttpSessionIdListner
    This interface defines only 1 method i.e sessionIdChanged(). This method will be called whenever the session ID is changed using the request's changeSessionId().

You can also register listener declaratively in deployment descriptor as below.
<listener>
   <listener-class>com.speakingcs.SessionListener</listener-class>
</listener>


0 comments:

Post a Comment

Note: only a member of this blog may post a comment.