开发者

Session state using guice

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 wri开发者_如何学运维te state less servlets/classes/applications)?


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 of Servlet, and Servlets must be bound in Singleton scope.

To resolve this, just bind your state (called Bar) in session scope and give your Foo constructor a Provider<Bar> argument (which will be filled in by Guice) so you can access the session-scoped state from the singleton-scoped Foo 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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜