播放框架处理会话状态 [英] Play framework handling session state

查看:87
本文介绍了播放框架处理会话状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于Play框架和Scala构建的Webapp.它是向用户显示一组问题,每个问题都有一组答案.有些问题的单选按钮类型为答案,有些问题的复选框为答案.当用户单击开始测试时,我调用控制器,获取带有答案的问题列表,并将结果作为案例类返回给视图模板.现在,当用户回答每个问题时,我需要保持测试状态.他可以上一个,下一个,而我需要跟踪他回答的所有问题.

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.

来自Java EE背景,我认为我可以将case类存储在会话中并在控制器中对其进行操作.不幸的是,这看起来并不像Play框架的会话是键值对String(字符串)而不是String(对象).我现在对应用程序一无所知,由于我对Play框架的使用经验有限,所以我想征求建议.

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.

推荐答案

Play框架中根本没有任何状态,因此,如果您希望跨多个HTTP请求保留一些数据,则可以方便地使用Session作用域,该作用域实际上使用key创建cookie /值对(字符串,字符串),并且它们的大小限制为4KB.

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.

我的建议是与Json一起使用,Play-json库很棒.如果您拥有使用JSON 读取/写入/格式化组合器的模型,那么它就不简单了.

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.

欢呼

这篇关于播放框架处理会话状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆