Today I spent a significant amount of time wrestling Jetty and Guice in order to get a very simple configuration up and running. Many articles I found on this topic are incomplete or out of date so here is a start to finish example of how to get Guice and Jetty working together without any web.xml.
Step 0 – Add these dependencies to your pom.xml if they aren’t there already
Step 1 – Create a module that describes your servlet configuration. Assume we have three servlets. One is called FooServlet and is served on the “/foo” path. One is called BarServlet and is served on the “/bar” path. One is called IndexServlet and is served for all other paths.
Step 2 – Create a module that contains your Guice bindings. We’ll assume you have something called NonServletImplementation you want bound to NonServletInterface that you’ll need to have injected into your servlets.
Step 3 – Instantiate your injector with all of your modules in the code where you want to create the server. If you have other modules you want to include you should include those as well.
Step 4 – Instantiate the server. You do not need to pass it the injector explicitly. Guice will handle that for you but you MUST instantiate the injector before this code runs.
1234567891011121314
intport=8080;Serverserver=newServer(port);ServletContextHandlerservletContextHandler=newServletContextHandler(server,"/",ServletContextHandler.SESSIONS);servletContextHandler.addFilter(GuiceFilter.class,"/*",EnumSet.allOf(DispatcherType.class));// You MUST add DefaultServlet or your server will always return 404sservletContextHandler.addServlet(DefaultServlet.class,"/");// Start the serverserver.start();// Wait until the server exitsserver.join();
Step 5 – Make sure your servlets are setup to use Guice and use the @Singleton annotation. Only the FooServlet skeleton is shown here but you should create the BarServlet and the IndexServlet as well.
importjavax.inject.Inject;importjavax.inject.Singleton;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;/** * Created by timmattison on 8/4/14. */@SingletonpublicclassFooServletextendsHttpServlet{privatefinalNonServletInterfacenonServletInterface;@InjectpublicFooServlet(NonServletInterfacenonServletInterface){this.nonServletInterface=nonServletInterface;}protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{// Do whatever you need to do with POSTs...}protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{// Do whatever you need to do with GETs...}}
If all goes well then everything will be wired up with Guice and your Jetty server is ready to rock. It turns out to be a lot simpler than working with the web.xml in my opinion since everything is mapped out explicitly in one place.