Play framework is being used by every Scala developer now a days. In this post we’ll learn about using Cookies in Play framework.
- Data stored in cookies are available till they expire or they are cleaned by user.
- We can set the expiration time of cookies.
- They can be made secure, but only for sites working on HTTPS.
- They can be used like a Scala collection.
Before start using Cookies in Play framework these two libraries have to imported.
import play.api.mvc.Cookie import play.api.mvc.DiscardingCookie
Storing the data in Cookie :
For the very first request we can store the values in Cookie as
Ok("Success").withCookies(Cookie("Org", "Knoldus Software LLP"))
This will save a Cookie in browser with name “Org” and store the value “Knoldus Software LLP” in it.
We can also set Cookies’ expiration time :-
Ok("Success").withCookies(Cookie("Org", "Knoldus Software LLP", Option(86400)))
You’ll have to give time in Seconds as Option(Int). Here we have set the expiration time = 86400 seconds i.e., 1 day. So, the Cookie will expire/will get delete after 1 day from browser. Like this, Cookie can be set for more/less time according to Application.
Retrieving data from Cookie:
We can retrieve data from Cookie by using “request”.
Discarding/Deleting the whole Cookie:
This will discard/delete the Cookie from browser even if the expiration time is not elapsed.
To check whether Cookies are being added in browser or not you can check it in your browser settings.