Grizzly 2 with guice 3

Γιώργος Βαλοτάσιος  30/05/2011

Playing with grizzly and guice. Considering that you already have a ServletModule and and a GuiceServletContextListener defined the above code should do the job.

The code

First a handler

import javax.servlet.ServletContextEvent;

import org.glassfish.grizzly.servlet.ServletHandler;

import com.google.inject.servlet.GuiceFilter;
import com.google.inject.servlet.GuiceServletContextListener;

public class GuiceHandler extends ServletHandler {
  private static final Logger logger = Logger.getLogger(GuiceHandler.class.getName());
  private final GuiceServletContextListener guiceServletContextListener;

  public GuiceHandler(GuiceServletContextListener guiceServletContextListener) {
    this.guiceServletContextListener = guiceServletContextListener;
    addFilter(new GuiceFilter(), "guiceFilter", null);
  }

  @Override
  public void start() {
    if (logger.isLoggable(Level.INFO)) logger.log(Level.INFO, String.format("Starting %s", GuiceHandler.class.getSimpleName()));
    guiceServletContextListener.contextInitialized(new ServletContextEvent(getServletCtx()));
    super.start();
  }

  @Override
  public void destroy() {
    super.destroy();
    guiceServletContextListener.contextDestroyed(new ServletContextEvent(getServletCtx()));
    if (logger.isLoggable(Level.INFO)) logger.log(Level.INFO, String.format("Destroyed %s", GuiceHandler.class.getSimpleName()));
  }
}

and the webserver:

import java.io.IOException;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.servlet.ServletHandler;

public class WebServer {

  public static void main(String[] args) {
    HttpServer server = HttpServer.createSimpleServer();

    ServletHandler handler = new GuiceHandler(new Live24WebApp());
    server.getServerConfiguration().addHttpHandler(handler, "/*");

    try {
      server.start();
      System.in.read();
      server.stop();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Still have to test it as I only had a simple servlet working!