7

How to use Cookies in Play framework

 3 years ago
source link: https://blog.knoldus.com/using-cookies-in-play-framework/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to use Cookies in Play framework

Reading Time: 2 minutes

Play framework is being used by every Scala developer now a days. In this post we’ll learn about using Cookies in Play framework.

Play has a stateless architecture so in order to keep the data across multiple HTTP request we can use Session & Flash. But both Session & Flash loose data as soon as browser is closed. So, to retain data even after closing the browser, we can use Cookies in Play framework. Cookies are not stored by the server, instead they are stored at the client side.

  • 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.

xxxxxxxxxx
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

xxxxxxxxxx
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 :-

xxxxxxxxxx
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:

xxxxxxxxxx
request.cookies.get("Org").get.value

We can retrieve data from Cookie by using “request”.

Discarding/Deleting the whole Cookie:

xxxxxxxxxx
Ok("Bye").discardingCookies(DiscardingCookie("Org"))

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK