[翻译]Session and Flash scopes
来源:互联网 发布:多益网络官网社会招聘 编辑:程序博客网 时间:2024/06/05 18:47
源https://www.playframework.com/documentation/2.5.x/JavaSessionFlash
Play中的不同
如果你必须在多个HTTP请求中保存数据,你可以将它们保存在Session中或者Flash scope中。保存在Session中的数据在整个用户会话中都是可用的,存储在flash scope中的数据只在下一个请求中可用。
Session和Flash中的数据并不是存储在server中,而是使用Cookies添加到下一个HTTP请求中,理解这一点非常重要。这意味着数据的大小有限(最大4KB),并且你只能存储String值。
Cookies被加密,以保证客户端不会修改cookie数据。Play session不可用作缓存。如果你需要缓存某个session的相关数据,你可以使用Play內建的缓存机制,并且使用session存储唯一ID将缓存数据关联到特定用户。
注意:session有一个非技术方面的时间限制,这在用户关闭网络浏览器时可能需要。如果你需要针对某个application的时间限制,在用户Session里面存一个timestamp(例如,最大session时间,最大非活动时间)就可以了。你可以通过配置play.http.session.maxAge(ms,毫秒)设置session cookies的最大时间。但是,注意这不能阻止黑客保存重用cookie。
在Session中存储数据
Session是Cookie,是HTTP首部,但是Play提供一个helper方法存储session值。
public Result login() { session("connected", "user@gmail.com"); return ok("Welcome!");}
同样,你可以从incoming session中移除任何值。
public Result logout() { session().remove("connected"); return ok("Bye");}
读取Session值
你可以从HTTP请求中读取incoming Session:
public Result index() { String user = session("connected"); if(user != null) { return ok("Hello " + user); } else { return unauthorized("Oops, you are not connected"); }}
删除整个session
如果你想要删除整个session,有一个特殊的操作:
public Result logout() { session().clear(); return ok("Bye");}
Flash scope
Flash scope与Session类似,但是有两点不同:
数据只为下一个请求保存
Flash cookie没有加密,用户可以修改它
重点:flash scope只用于在简单的non-Ajax应用中传输success/error信息。因为数据仅仅为下一个请求保存,然而在复杂(组合的)Web application中不能保证请求的顺序,Flash scope会受竞争条件(race condition)影响。
例如,存储一个item之后,你可能需要将用户跳转到index页,你可能想要在index页中展示错误说明保存成功。在存储action里面,你可能添加success信息到flash scope:
public Result save() { flash("success", "The item has been created"); return redirect("/home");}
在index action中,你检查success信息是否保存在flash scope内,如果成功,渲染出来:
public Result index() { String message = flash("success"); if(message == null) { message = "Welcome!"; } return ok(message);}
flash值在Twirl模板中也是可用的。例如:
@if(flash.containsKey("success")) { @flash.get("success")} else { Welcome!}
- [翻译]Session and Flash scopes
- play framework2学习之旅<2.4>Session and Flash scopes
- [Play Framework]Session and Flash scopes——用Play操作Session和Flash数据
- 1.4_Session and Flash scopes
- spring 学习1-Request, session, and global session scopes|(Initial web configuration)
- Python Scopes and Namespaces
- red5 Scopes and Contexts 作用域 上下文
- red5 Scopes and Contexts 作用范围
- Difference between Scopes and Namespaces in python
- 待翻译---- Understanding Spring MVC Model and Session Attributes
- Java Spring Tutorial -- Singleton and Prototype Bean Scopes
- 10.7 Scopes
- Bean scopes
- Ruby Scopes
- Bean scopes
- angularjs Scopes
- Understanding Scopes
- flash读取Session
- mybatis配置犄角旮旯
- 守护进程
- JSP隐式对象
- Intent传递数据从一个Activity到另一个Activity
- Python
- [翻译]Session and Flash scopes
- 给docker容器分配静态ip地址
- 正则表达式符号笔记
- maven的pom.xml配置文件详解
- matlab2017a doc 关联注册码
- SVN服务的搭建(三)
- 变量作用域
- Glide加载图片,同一url更换图片不更新的问题
- 2017年6月16日,周结(十七),一些简单的算法题(三)