Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top