Efficiently using Session & Flash in Play framework

Play framework is being the love of every Scala developer now a days. In this post we’ll learn about using Session & Flash scopes in Play framework.

Play has a stateless architecture so in order to keep the data across multiple HTTP request we can use Session & Flash. Session and Flash data are not stored by the server but are added to each subsequent HTTP request, using the cookie mechanism. This result in to the limitation of data size that we want to keep in Session or Flash. Generally we can store data up to 4KB in Session or Flash.Session :

– Data stored in the Session are available during the whole user session.
– Cookie values are signed with a secret key so the client can’t modify the cookie data.

Storing the data in Session :

For the very first request we can store the values in Session as

This’d start a new session and store the values.

For the subsequent requests in order to store more data in session you can use it like :

This’d keep the previously stored values in session and would add more data in Session.

Is there a way we can access request or use request.session.get(“”) something in some normal method and not an action? I need to access request but want to call some other method from it and not return some result

Session never expire by just closing browser or just using logout button. As HTTP is a stateless protocol, so we use session-id to keep track of multiple HTTP request of authenticated user and differentiate from other users as well. So, session-id have same importance as password have. After logout, if session-id is not expire by the server end. Then, user don’t need their credentials again to log-in. IF any how anyone get session-id, HE/SHE log-in into the application. So, Session – id must be expire by server end.