How to @Inject a HttpSession object in a service l

2019-04-15 08:34发布

问题:

I have such a dirty code in my GWT app, some of the classes of my service layer depend on an HttpSession object. So for example, in one of my DAO (which was a GWT-RPC endpoint) I have something like this :

public class MyExampleDAO extends RemoteServiceServlet {
   public findItems() {
       // here I need to get the object session to retrieve the currently logged in user in order to query for all its items...
   }
}

The problem is that, I am currently migrating the code to use RequestFactory. My DAO will not be a GWT-RPC endpoint anymore. So no need to extend RemoteServiceServlet then ...

Do you know how I can get/inject (probably with Guice) my dependency to HttpSession Object, knowing that my class does not extend RemoteServiceServlet anymore?

回答1:

getThreadLocalRequest().getSession() should do it. RequestFactoryServlet has a similar (but static) getThreadLocalRequest() method that you can access from your service. Otherwise, you can get Guice to inject a Provider<HttpSession>, have a look at these projects https://github.com/mgenov/injecting-request-factory and https://github.com/etiennep/injected-requestfactory for some sample code using Guice with RequestFactory.