简体   繁体   中英

Passing in objects to GWT servlets via servlet attributes (server-side) or “Dependency Injection”

How do I pass objects from non-GWT server-side code (eg regular server code) to the GWT "servlet" (still server-side code), specifically a RemoteServiceServlet ?

My GWT server-side code consists of RPC-type RemoteServiceServlet s to which I can't seem to get a reference so I can't pass in my real/fake object in testing mode or add servlet attributes. I can't see any way to simply pass objects in (dependency-injection style) as I have no access to the Server object as GWT seems to instantiate it deep within its internals, so what are my options?

PS I don't want to use a full-blown DI framework such as GIN/Juice - I find them to much magic. I just want a way to access the instance of a GWT servlet and pass stuff to it.

Let me start out by saying, if you haven't already, I highly recommend watching this Google I/O presentation on GWT Architecture best practices . I found it very useful and it's where most of the following came from.

What I did was create an abstract "dispatch" servlet that extends GWT's RemoteServiceServlet. Every module I have has only one service (that extends my abstract dispatch service) with which I register a set of request handlers. All GWT service calls for a given GWT module come into that module's dispatch service, which looks at the type of request and dispatches it to the appropriate request handler. The request handlers, in effect, handle the work that previously resided in the service servlet. Besides making your life easier by having fewer servlets to register in your web.xml (not to mention avoiding the extra interfaces GWT requires), you can more easily control the dispatcher object that handles all the actual dispatching. You can, for example, pass whatever real/mock object you like into these request handlers since you, and not the web container, are responsible for instantiating them.

And though I rolled my own, the gwt-dispatch project exists for this very purpose.

Hope this helps.

Servlet containers are designed to not allow direct access to the servlets that they host; that's why you've found it difficult to get any kind of handle to a servlet.

Rather, refactor the code that is currently in your servlets into separate request-handler classes, and have your serlvets call into them.

For testing purposes you can hook your testing framework, or your client code, to the request-handler classes directly. That's how people generally solve the problem you've run into.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM