Play framework handling session state

前端 未结 3 1708
孤城傲影
孤城傲影 2020-12-17 19:59

I have a Webapp that is built on top of the Play framework and Scala. It is about presenting the user with a set of questions with each question having a set of answers. Som

3条回答
  •  余生分开走
    2020-12-17 20:41

    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

提交回复
热议问题