Custom code execution before Session expires
Sometime in our application, it is required to execute custom code before session is going to expire or timeout
In such case,Hybirs provides a mechanism to write custom code.
Let’s see how we can do that
We can achieve this by providing a custom sessionCloseStrategy Spring bean in the web Spring context
This strategy class has to either implement the sessionCloseStrategy interface or can extend the DefaultSessionCloseStrategy class
We need to override closeSessionInHttpSession() method of SessionCloseStrategy
Inside this SessionCloseStrategy() method, we can write our custom code
Let’s define this strategy with custom code
Step 1
First create a class which extends DefaultSessionCloseStrategy
- public class StorefrontSessionCloseStrategy extends DefaultSessionCloseStrategy
- {
- @Override
- public void closeSessionInHttpSession(final HttpSession httpSession)
- {
- //Write custom code here
- //We can also use session values here as session is available here
- super.closeSessionInHttpSession(httpSession);
- }
- }
public class StorefrontSessionCloseStrategy extends DefaultSessionCloseStrategy { @Override public void closeSessionInHttpSession(final HttpSession httpSession) { //Write custom code here //We can also use session values here as session is available here super.closeSessionInHttpSession(httpSession); } }
Step 2
Register the above class as a spring bean in the application context
- <alias alias="sessionCloseStrategy" name="storefrontSessionCloseStrategy"/>
- <bean id="storefrontSessionCloseStrategy " class=“com.kb.storefront.StorefrontSessionCloseStrategy "/>
<alias alias="sessionCloseStrategy" name="storefrontSessionCloseStrategy"/> <bean id="storefrontSessionCloseStrategy " class=“com.kb.storefront.StorefrontSessionCloseStrategy "/>
Note :
Bean alias must exactly be sessionCloseStrategy in order for the bean to be picked up by hybris
When session is about to expire, above overridden closeSessionInHttpSession() method is called automatically by Hybris.
Session is available inside this method and gets closed immediately after leaving this method
Note :
It is very important to call “super.closeSessionInHttpSession(httpSession)” at the end of the overridden method as this deals with the correct closing and disposal of the Session