Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

scala - Play framework handling session state

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. Some of the questions have radio button types an answers and some have check boxes as answers. When the user clicks start test, I call the controller, fetch the list of questions with its answers and return the result as a case class to the view template. I now need to maintain the state of the test as the user answers each question. He can go previous, next and I need to keep track of all the questions that he answered.

Coming from a Java EE background, I thought I can store the case class in the session and manipulate it in my controller. But that unfortunately does not look like that as the Play framework's session is a key value pair of String, String and not a String, Object. I'm now stuck with my app and since my experience with the Play framework is limited, I would like to ask for suggestions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...