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.
– 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
Ok("Success").withSession("Org"-> "Knoldus Software LLP")
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 :
val sesssionToMaintain = request.session + ("location" -> "New Delhi") Ok("Success").withSession(sesssionToMaintain)
This’d keep the previously stored values in session and would add more data in Session.
Retrieving the data from session:
"Value of 'Org' from Session : " + request.session.get("Org")
Discarding the whole session :
Session Expiry : Session expires when the user closes the web browser.
– Data stored in the Flash scope are available to the next request only.
– Cookie is not signed, making it possible for the user to modify it.
Storing the data in Flash :
Redirect("/").flashing("Org"->"Knoldus Software LLP")
Retrieving the data from Flash:
"Value of 'Org' from Flash : " + request.flash.get("Org")
Retrieving the values on views :
To retrieve the Flash scope value in your view, just add an implicit with Flash:
@()(implicit flash: Flash) ... ... @flash.get("Org").getOrElse("No Company Found") ...