Kohei Nozaki's blog 

Lean example of Tomcat 8 + Guice 4

Posted on Monday Aug 03, 2015 at 06:56PM in Technology

I prefer Java EE stack usually, but I need to learn a Tomcat based stack for some reasons these days. in this entry, I introduce you a very simple example of Tomcat 8 + Guice 4 app which uses GuiceFilter and GuiceServletContextListener so that bring Guice to a Servlet based web application.

The entire project which based on Maven can be obtained from My GitHub repository.




<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"






We need to declare servlet mappings and the mappings between interfaces and implementations here.

public class MyGuiceServletConfig extends GuiceServletContextListener {
    protected Injector getInjector() {
        return Guice.createInjector(new ServletModule() {
            protected void configureServlets() {

Service class

We use a pair of a very simple implementation of a service class. it simply creates a greetings which uses an argument.


public interface MyService {
    String hello(String name);


public class MyServiceImpl implements MyService {
    public String hello(String name) {
        return "Hello, " + name;


Note that we use @javax.inject.Singleton and @javax.inject.Inject annotations, that are standardized JSR API.

public class MyServlet extends HttpServlet {

    private MyService myService;

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

Test run

After deployment, send a request to check the response:

$ curl http://localhost:8080
Hello, Guice

Other things/functions need to be studied

  • Transaction management

  • CDI Producer equivalent

  • AOP

  • Automatic implementation scanning/binding


This is an excellent bare-bones example showing the base "root level" mapping which seems to work ok, but there is a quirky difference between web.xml's filter-mapping/url-pattern behavior and the GuiceServletContextListener's serve(urlPattern) behavior for non-root-level paths. The JEE pattern matches more actual urls. For example, if the url-pattern were "/someresource/*" it would match "/myresource/metadata" and "/myresource?param1=2" and even "/myresource" but serve("/myresource/*") won't match all of those, and serve("/myresource") won't either. You would need to serve() both patterns to get the same coverage.

Posted by Fred on April 21, 2020 at 09:52 AM JST #

Leave a Comment

HTML Syntax: NOT allowed