Rectangle 27 0

java Simple Example with Guice Servlets?


<c:forEach items="${names}" var="name">
  ${name}<br/>
</c:forEach>
@Override
protected Injector getInjector() {
    return Guice.createInjector(
            new ServletModule() {
                @Override protected void configureServlets() {
                    serve("/index.html").with(IndexController.class);
                }
            },
            new ListModule());
}
@Singleton
public class IndexController extends HttpServlet {

    @Inject ListService listService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("names", listService.names());
        req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req, resp);
    }

}
DummyListService
GuiceServletContextListener
IndexController
ListModule
ListService
public class DummyListService implements ListService {
    public List<String> names() {
        return Arrays.asList("Dave", "Jimmy", "Nick");
    }
}
public class ListModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(ListService.class).to(DummyListService.class);
    }
}
public interface ListService {
    List<String> names();
}

@Dave Ah...I completely missed that. Thanks for the help. VERY much appreciated.

@Dave thanks for this incredible example. One question...should ListModule extend ServletModule or is that not necessary?

@Robert No problem :) It all seems a little unwieldy to me, although I'm not familiar with the Guice IDE plugin yet.

@Robert Nope; it's not a servlet module. Servlet modules are explicitly for configuring request handlers, AFAICT. Plus you can't use a ServletModule.configure() to do the same work, since it's a final method.

To get started, here's an example that injects a service returning a list of names into an index controller. (No trickery in this example, everything is explicit.)

Note