如何在play框架中的会话中存储对象(不是字符串)? [英] How to store object (not string) in session in play framework?

查看:142
本文介绍了如何在play框架中的会话中存储对象(不是字符串)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个学校项目,我必须使用Java。最近我找到了play框架,我想尝试使用它。它很容易快速启动,但我遇到了会话问题。



本质上是无状态的,play会将整个会话发送给cookie中的用户并在下一个请求,所以它只允许会话中有限数量的数据。



我想要做的是在用户登录时从数据库中获取User对象,并将其保存在会话中,所以我可以从模板中访问它等等(我在User类中有一些方法需要调用以自定义UI),但是如果我放置User对象,则调用其toString方法并将其放入会话中。 / p>

我发现推荐的方法是将大量数据放入Cache中,但我不知道如何从模板中访问它(我想我可以用@创建方法)在注释之前将用户添加到renderArgs,但这对我来说似乎不太干净)。另一个问题是Cache的生命周期有限,所以我的对象可能会消失。



有没有人遇到过这类问题?



有没有办法在游戏中使用服务器端会话?我不需要这个项目的REST功能,所以,就我而言,应用程序可以保存状态......

解决方案

使用Java序列化将Hashmap序列化为文件或数据库。将文件或id列命名为存储在用户cookie中的唯一标识符。然后在序列化hashmap之前将User对象放在hashmap中。现在您有了一个可以访问的持久性存储。当框架忘记User对象或任何其他会话信息时,您可以反序列化Hashmap。然后编写一些静态辅助方法,静态Object SessionDB.get(String id,String key)和SessionDB.put(String id,String key,Object value)。我在自制框架上使用此方法在小型服务器场上存储会话信息。我当然使用数据库,而不是文件系统。


I have a project for school and I have to use Java. Recently I found play framework and I want to try to use it. It's easy enough for a quick start, but I ran into a problem with session.

Being stateless by its nature, play sends entire session to user in cookie and receives it on next request, so it allows only limited amount of data in session.

What I want to do is to fetch User object from DB on user login, and keep it in session, so I could access it from templates and so on (I have some methods in User class that I need to call in order to customize UI), but if I put User object, play calls its toString method and puts that in session.

I found that recommended way is to put larger amount of data into Cache, but I don't know how to access it from template (I guess I could make method with @Before annotation and add user to renderArgs, but that does not seem very clean to me). Another problem is that Cache has limited lifetime, so my object can disappear.

Does anyone has experience with this kind of problems?

Is there any way to use server side session with play? I don't need REST functionality for this project, so, as far as I am concerned, application can save state...

解决方案

Use Java Serialization to serialize a Hashmap to a file or to the database. Name the file or id column after a unique identifier you store in the user's cookie. Then put the User object in the hashmap before you serialize the hashmap. Now you have a persistent store that you can access. When the framework forgets the User object or any other session information, you can deserialize the Hashmap. Then write some static helper methods, static Object SessionDB.get(String id, String key) and SessionDB.put(String id, String key, Object value). I use this method on my homemade framework to store session information over a small server farm. Of course I use the database, not a file system.

这篇关于如何在play框架中的会话中存储对象(不是字符串)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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