3

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)?

Stan Kurilin
  • 15,614
  • 21
  • 81
  • 132

2 Answers2

3

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.

Waldheinz
  • 10,399
  • 3
  • 31
  • 61
2

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)

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Ok. Thanks. But for what purpose ServletScopes was created? And where I should put my session scoped variables? – Stan Kurilin Feb 23 '11 at 13:41
  • 1
    Guice actually does create servlets when you're using the guice-servlet extension. It requires that the servlets be singletons because it is consistent with the servlet spec. – ColinD Feb 23 '11 at 22:02