使用 guice 的会话状态
我有一些会话范围的状态。保存它的第一个想法是会话范围的 servlet。所以我像这样绑定我的 servlet
bind(Foo.class).in(ServletScopes.SESSION);
但是我得到了一个异常
<块引用>javax.servlet.ServletException:Servlet 必须绑定为单例。 Key[type=Foo, annotation=[none]] 未绑定在单例范围内。
那么 servlet 不能具有 ServletScopes 的作用域吗?处理会话状态的正确方法是什么(是的,当然最好编写无状态的 servlet/类/应用程序)?
I've some session scoped state. First idea to hold it was session scoped servlets. So I bind my servlet like this
bind(Foo.class).in(ServletScopes.SESSION);
But I get an exception
javax.servlet.ServletException: Servlets must be bound as singletons. Key[type=Foo, annotation=[none]] was not bound in singleton scope.
So servlets can't have scope from ServletScopes? Whats the right way to deal with session state (yeah, of course it's better to write state less servlets/classes/applications)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据我的理解,您可以将任何您想要的内容绑定到会话范围,问题是在您的示例中
Foo
似乎是Servlet
的子类,并且 Servlet 必须绑定在Singleton
范围内。要解决此问题,只需在会话范围中绑定您的状态(称为
Bar
),并为您的Foo
构造函数提供一个Provider< /code> 参数(将由 Guice 填充),以便您可以从单例范围的
Foo
Servlet 访问会话范围的状态。From my understanding you can bind whatever you want to the session scope, the problem is that in your example
Foo
seems to be an subclass ofServlet
, and Servlets must be bound inSingleton
scope.To resolve this, just bind your state (called
Bar
) in session scope and give yourFoo
constructor aProvider<Bar>
argument (which will be filled in by Guice) so you can access the session-scoped state from the singleton-scopedFoo
Servlet.servlet 不是由 Guice 创建的,而是由 servlet 容器创建的。它们是单例的:servlet 容器只创建一个实例来服务所有客户端的所有请求。
因此将它们绑定到会话范围是没有意义的:Guice 无法为每个会话创建一个不同的 servlet 实例。
servlet 应该始终是无状态的(即它的状态对于所有客户端来说应该是全局的,并且可以以线程安全的方式访问)
servlets are not created by Guice, but by the servlet container. And they are singletons : only one instance is created by the servlet container to serve all the requests of all the clients.
So binding them to session scope has no sense : Guice can not create one different servlet instance per session.
A servlet should always be stateless (i.e. its state should be global to all the clients, and be accessed in a thread-safe way)