com.google.inject.servlet
Class ServletModule

java.lang.Object
  extended by com.google.inject.AbstractModule
      extended by com.google.inject.servlet.ServletModule
All Implemented Interfaces:
Module

public class ServletModule
extends AbstractModule

Configures the servlet scopes and creates bindings for the servlet API objects so you can inject the request, response, session, etc.

As of Guice 2.0, you can subclass this module to register servlets and filters in the configureServlets() method.


Nested Class Summary
static interface ServletModule.FilterKeyBindingBuilder
           
static interface ServletModule.ServletKeyBindingBuilder
           
 
Constructor Summary
ServletModule()
           
 
Method Summary
protected  void configure()
          Configures a Binder via the exposed methods.
protected  void configureServlets()
          Servlet Mapping EDSL
protected  ServletModule.FilterKeyBindingBuilder filter(String urlPattern, String... morePatterns)
           
protected  ServletModule.FilterKeyBindingBuilder filterRegex(String regex, String... regexes)
           
protected  ServletModule.ServletKeyBindingBuilder serve(String urlPattern, String... morePatterns)
           
protected  ServletModule.ServletKeyBindingBuilder serveRegex(String regex, String... regexes)
           
 
Methods inherited from class com.google.inject.AbstractModule
addError, addError, addError, bind, bind, bind, bindConstant, binder, bindInterceptor, bindScope, configure, convertToTypes, currentStage, getProvider, getProvider, install, requestInjection, requestStaticInjection, requireBinding, requireBinding
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ServletModule

public ServletModule()
Method Detail

configure

protected final void configure()
Description copied from class: AbstractModule
Configures a Binder via the exposed methods.

Specified by:
configure in class AbstractModule

configureServlets

protected void configureServlets()

Servlet Mapping EDSL

Part of the EDSL builder language for configuring servlets and filters with guice-servlet. Think of this as an in-code replacement for web.xml. Filters and servlets are configured here using simple java method calls. Here is a typical example of registering a filter when creating your Guice injector:

   Guice.createInjector(..., new ServletModule() {

     @Override
     protected void configureServlets() {
       serve("*.html").with(MyServlet.class)
     }
   }
 
This registers a servlet (subclass of HttpServlet) called MyServlet to service any web pages ending in .html. You can also use a path-style syntax to register servlets:
       serve("/my/*").with(MyServlet.class)
 
Every servlet is required to be a singleton and will implicitly be bound as one if it isn't already. Mapping a servlet that is bound under any other scope is an error.

Dispatch Order

You are free to register as many servlets and filters as you like this way. They will be compared and dispatched in the order in which the filter methods are called:

   Guice.createInjector(..., new ServletModule() {

     @Override
     protected void configureServlets() {
       filter("/*").through(MyFilter.class);
       filter("*.css").through(MyCssFilter.class);
       // etc..

       serve("*.html").with(MyServlet.class);
       serve("/my/*").with(MyServlet.class);
       // etc..
      }
    }
 
This will traverse down the list of rules in lexical order. For example, a url "/my/file.js" (after it runs through the matching filters) will first be compared against the servlet mapping:
       serve("*.html").with(MyServlet.class);
 
And failing that, it will descend to the next servlet mapping:
       serve("/my/*").with(MyServlet.class);
 
Since this rule matches, Guice Servlet will dispatch to MyServlet. These two mapping rules can also be written in more compact form using varargs syntax:
       serve("*.html", "/my/*").with(MyServlet.class);
 
This way you can map several URI patterns to the same servlet. A similar syntax is also available for filter mappings.

Regular Expressions

You can also map servlets (or filters) to URIs using regular expressions:
    serveRegex("(.)*ajax(.)*").with(MyAjaxServlet.class)
 
This will map any URI containing the text "ajax" in it to MyAjaxServlet. Such as:
  • http://www.google.com/ajax.html
  • http://www.google.com/content/ajax/index
  • http://www.google.com/it/is_totally_ajaxian

Initialization Parameters

Servlets (and filters) allow you to pass in init params using the <init-param> tag in web.xml. You can similarly pass in parameters to Servlets and filters registered in Guice-servlet using a Map of parameter name/value pairs. For example, to initialize MyServlet with two parameters (name="Dhanji", site="google.com") you could write:
  Map<String, String> params = new HashMap<String, String>();
  params.put("name", "Dhanji");
  params.put("site", "google.com");

  ...
      serve("/*").with(MyServlet.class, params)
 

Binding Keys

You can also bind keys rather than classes. This lets you hide implementations with package-local visbility and expose them using only a Guice module and an annotation:
  ...
      filter("/*").through(Key.get(Filter.class, Fave.class));
 
Where Filter.class refers to the Servlet API interface and Fave.class is a custom binding annotation. Elsewhere (in one of your own modules) you can bind this filter's implementation:
   bind(Filter.class).annotatedWith(Fave.class).to(MyFilterImpl.class);
 
See Binder for more information on binding syntax.


filter

protected final ServletModule.FilterKeyBindingBuilder filter(String urlPattern,
                                                             String... morePatterns)
Parameters:
urlPattern - Any Servlet-style pattern. examples: /*, /html/*, *.html, etc.

filterRegex

protected final ServletModule.FilterKeyBindingBuilder filterRegex(String regex,
                                                                  String... regexes)
Parameters:
regex - Any Java-style regular expression.

serve

protected final ServletModule.ServletKeyBindingBuilder serve(String urlPattern,
                                                             String... morePatterns)
Parameters:
urlPattern - Any Servlet-style pattern. examples: /*, /html/*, *.html, etc.

serveRegex

protected final ServletModule.ServletKeyBindingBuilder serveRegex(String regex,
                                                                  String... regexes)
Parameters:
regex - Any Java-style regular expression.