Play framework handling session state

◇◆丶佛笑我妖孽 提交于 2019-11-29 06:34:43

There is no state at all in Play framework so if you want to keep some data across multiple HTTP requests its handy to use Session scope that actually creates cookies with key/value pair (String, String) and they are limited to 4KB size.

My suggestion is to do it with Json, Play-json library is awesome. IF you have models with JSON Read/Write/Format combinators than its simple.

Ok(render(Questions)).withSession("answers" -> Json.prettyPrint(Json.toJson(Answer)))

Reading a session value can be done like this:

def index = Action { implicit request =>
      session.get("answers").map { answers =>
        val jsValueAnswers: JsValue = Json.parse(answers)
        val answersModel: YourAnswerModel = Json.fromJson(jsValueAnswers) 
        Ok("Got previous answers and created session cookie with them")
        .withSession("answers2" -> Json.prettyPrint(Json.toJson(answersModel)))
      }
    }

Hope this help you a bit.

Cheers

Play only supports Strings for sessions because it stores all session state in cookies - this means Play nodes can scale without the need for any sort of clustering/state sharing tech.

If the data you want to store is small (less than 2k), then just serialise it into JSON, or it sounds like in your case, even simpler would be to serialise it into a comma separated list of answers.

Otherwise, you can store it in a cache such as memcached or redis.

Play is a framework designed to be stateless, so you do not find any concrete concept of server side session. Of course, this is not strictly prohibited, if you need it, as in this case, you can use a server-side technology (cache or database) as a container for your items and Play-cookie session for storing the access key string.

This is an example of storing object using Play Cache:

import play.api.cache.Cache
import play.api.Play.current

val key = UUID.randomUUID.toString
Cache.set(key, yourModel, 0)
Ok.withSession("answer_key" -> key)

and this is an example of retrieval:

import play.api.cache.Cache
import play.api.Play.current

val key = session.get("answer_key").getOrElse("none")
val yourModel = Cache.getAs[ModelClass](key).getOrElse(//whatever you want if not exists)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!