本文介绍了如何在Google Guice中使用Play Framework的请求和会话范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Play(Java)Framework项目中使用的是Guice for Dependency Injection,并且努力了解会话"的概念如何与Guice and Play最佳结合使用?

I am using Guice for Dependency Injection in my Play (Java) Framework project, and struggling to understand how the concept of "session" is best used with Guice and Play?

我知道Play是无状态的,除了可以将值存储在Cookie中之外,实际上没有会话的概念.我对Guice和Play的理解是,尽管Guice文档描述了支持不同的作用域(单个作用域,会话,请求,无作用域),因为我们在每个请求中都实例化了一个新的注入器,但适用于Play的唯一作用域是单例和否"范围".

I know that Play is stateless and there really is no concept of a session, other than that you can store values in a cookie. My understanding with Guice and Play is that, while Guice documentation describes supporting different scopes (singleton, session, request, no scope), because we are instantiating a new injector with every request, the only scopes that apply to Play are singleton and "no scope".

让我感到困惑的是:使用Guice and Play模拟"会话的最佳方法是什么?我应该定义一个自定义范围"吗?

Where I am confused is: what is the best way to "simulate" a session using Guice and Play? Should I define a "custom scope"?

请注意,我正在使用Redis存储会话数据.这是我正在考虑的一些选项:

Note that I am using Redis to store my session data. Here are some options I'm thinking about:

  • 编写一个单例Guice类,用作Redis的薄包装器
  • 编写一个无作用域"的Guice类,该类使用ctx()对象来获取和设置Java对象
  • Write a singleton Guice class that serves as a thin wrapper around Redis
  • Write a "no scope" Guice class that uses the ctx() object to get and set Java objects

这里是否有标准做法,或者在我的Play应用中设置会话概念时可能会遵循的其他任何准则?

Is there a standard practice here, or any other guidelines I might follow to setup a session concept in my Play app?

推荐答案

Play中没有会话.如果要建立会话,则必须使用动作组合和WrappedRequest提供一个会话:在这种情况下,您需要一个具有会话ID的cookie,然后需要一个在Redis中查找会话ID并返回的服务您的会话数据,因此您可以将其放入WrappedRequest中.

There is no session in Play. If you want a session, you're going to have to provide one using action composition and WrappedRequest: in this case, you want a cookie with a session id, and then you want a service that looks up the session id in Redis and returns you the session data so you can put it in a WrappedRequest.

一旦您有一个WrappedRequest公开了您的会话数据,就可以引用它:request.user,request.context等.是的,您可以直接使用request.injector公开Guice查找,但这有点更易受攻击,而不是类型安全的.

Once you've got a WrappedRequest that exposes your session data, you can refer to it: request.user, request.context, etc. Yes, you can expose Guice lookups directly with request.injector, but that is a bit more hacky, and not as type safe.

这篇关于如何在Google Guice中使用Play Framework的请求和会话范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 20:45