A better ServletModule

63 views
Skip to first unread message

Jeff Schnitzer

unread,
Aug 26, 2015, 2:36:46 AM8/26/15
to google-guice
I use JAXRS a lot, tied into Guice. It's great - my resources are instantiated, get their injections, executed, then thrown away. But sometimes I need to use something lower level, so I mount a servlet with ServletModule.

The problem is that servlets suck. They have to be singletons and they have an awkward API, passing HttpServletRequest and HttpServletResponse around. Not at all like the simple throwaway instances that I get in JAXRS-land. This is what I really want:

public class MyServletModule extends BetterServletModule {
    public void configureRunnables() {
        serve("/somepath").with(MyClassThatImplementsRunnable.class);
    }
}

Now anyone could make a class like this:

public class MyAction implements Runnable {
    private final HttpServletResponse response;

    @Inject
    public MyAction(HttpServletResponse response) {
        this.response = response;
    }

    public void run() {
        response.getWriter().println("Hello, world");
    }
}

It's pretty easy to imagine that by injecting more sophisticated objects (that themselves abstract request/response), you could have a pretty elegant mini-web-framework without a lot of effort. Less need for Provider<?>s everywhere.

I looked at the implementation of ServletModule and didn't really understand what's going on. How hard would it be to implement something like what I describe? Can someone suggest a general approach that would get me started in the right direction? Even better, has anyone already done this?

Thanks,
Jeff
Reply all
Reply to author
Forward
0 new messages