Hi All,
 
I did a little enhancement for servlet route mapping for my own project, it 
could map a URL into a method within a servlet (Just like struts2) rather 
than a whole servlet. It works locally fine for me currently.
 
I just changed 3 source class a little very carefully. But I am still not 
sure whether I coded in a correct way. Especially under multi-thread 
situation.
 
If someone could take a review of these changes will be mush appreciated ! 
Many thanks!
 
I introduced 'at' to tell Guice bind the URL at the specified method:
 
return Guice.createInjector(new ServletModule() {
   @Override
   protected void configureServlets() {
    serve("/index").with(IndexServlet.class).at("index");
    serve("/index/update").with(IndexServlet.class).at("update");
    serve("/index/delete").with(IndexServlet.class).at("delete");
   }
  });
 
The method mush be follow :
 
public %AnyReturnType% %methodName%(HttpServletRequest request, 
HttpServletResponse response) [@Optional throws ServletException, 
IOException]
 
Here is an example of my servlet :
 
@Singleton
public class IndexServlet extends HttpServlet {
 private static final long serialVersionUID = 3594023761495055538L;
 
 public void index(HttpServletRequest request, HttpServletResponse 
response) {
  System.out.println("index");
 }
 public String update(HttpServletRequest request, HttpServletResponse 
response) {
  System.out.println("update");
  return "Hello";
 }
 public Object delete(HttpServletRequest request, HttpServletResponse 
response)throws ServletException, IOException {
  System.out.println("delete");
  return new Object();
 }
}
 
 
Attached is the source code I made changes. Many thanks again!

-- 
You received this message because you are subscribed to the Google Groups 
"google-guice" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/google-guice/-/oWNatvkmrWYJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/google-guice?hl=en.

/**
 * Copyright (C) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.inject.servlet;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServlet;

import com.google.common.collect.Sets;
import com.google.inject.Binder;
import com.google.inject.Key;
import com.google.inject.internal.UniqueAnnotations;

/**
 * Builds the guice module that binds configured servlets, with their
 * wrapper ServletDefinitions. Is part of the binding EDSL. Very similar to
 * {@link com.google.inject.servlet.FiltersModuleBuilder}.
 *
 * @author Dhanji R. Prasanna ([email protected])
 */
class ServletsModuleBuilder {
  
  private final Set<String> servletUris = Sets.newHashSet();
  private final Binder binder;
  
  public ServletsModuleBuilder(Binder binder) {
    this.binder = binder;
  }

  //the first level of the EDSL--
  public ServletModule.ServletKeyBindingBuilder serve(List<String> urlPatterns) {
    return new ServletKeyBindingBuilderImpl(urlPatterns, UriPatternType.SERVLET);
  }

  public ServletModule.ServletKeyBindingBuilder serveRegex(List<String> regexes) {
    return new ServletKeyBindingBuilderImpl(regexes, UriPatternType.REGEX);
  }

  //non-static inner class so it can access state of enclosing module class
  class ServletKeyBindingBuilderImpl implements ServletModule.ServletKeyBindingBuilder {
    private final List<String> uriPatterns;
    private final UriPatternType uriPatternType;

    private ServletKeyBindingBuilderImpl(List<String> uriPatterns, UriPatternType uriPatternType) {
      this.uriPatterns = uriPatterns;
      this.uriPatternType = uriPatternType;
    }

    public ServletModule.ServletMethodBindingBuilder with(Class<? extends HttpServlet> servletKey) {
      return with(Key.get(servletKey));
    }

    public ServletModule.ServletMethodBindingBuilder with(Key<? extends HttpServlet> servletKey) {
      return with(servletKey, new HashMap<String, String>());
    }

    public ServletModule.ServletMethodBindingBuilder with(HttpServlet servlet) {
      return with(servlet, new HashMap<String, String>());
    }

    public ServletModule.ServletMethodBindingBuilder with(Class<? extends HttpServlet> servletKey,
        Map<String, String> initParams) {
      return with(Key.get(servletKey), initParams);
    }

    public ServletModule.ServletMethodBindingBuilder with(Key<? extends HttpServlet> servletKey,
        Map<String, String> initParams) {
      return with(servletKey, initParams, null);
    }

    private ServletModule.ServletMethodBindingBuilder with(Key<? extends HttpServlet> servletKey, Map<String, String> initParams,
        HttpServlet servletInstance) {
      return new ServletMethodBindingBuilderImpl(servletKey, initParams, servletInstance);
    }

    public ServletModule.ServletMethodBindingBuilder with(HttpServlet servlet,
        Map<String, String> initParams) {
      Key<HttpServlet> servletKey = Key.get(HttpServlet.class, UniqueAnnotations.create());
      binder.bind(servletKey).toInstance(servlet);
      return with(servletKey, initParams, servlet);
    }
    
    class ServletMethodBindingBuilderImpl implements ServletModule.ServletMethodBindingBuilder {
    	private final Key<? extends HttpServlet> servletKey;
    	private final Map<String, String> initParams;
        private final HttpServlet servletInstance;
		public ServletMethodBindingBuilderImpl(
				Key<? extends HttpServlet> servletKey,
				Map<String, String> initParams, HttpServlet servletInstance) {
			this.servletKey = servletKey;
			this.initParams = initParams;
			this.servletInstance = servletInstance;
		}
		@Override
		public void at(String methodName) {
			for (String pattern : uriPatterns) {
		        // Ensure two servlets aren't bound to the same pattern.
		        if (!servletUris.add(pattern)) {
		          binder.addError("More than one servlet was mapped to the same URI pattern: " + pattern);
		        } else {
		          binder.bind(Key.get(ServletDefinition.class, UniqueAnnotations.create())).toProvider(
		              new ServletDefinition(pattern, servletKey, UriPatternType
		                  .get(uriPatternType, pattern), initParams, servletInstance, methodName));
		        }
		    }
		}
    	
    }
  }
}
/**
 * Copyright (C) 2006 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.inject.servlet;

import static com.google.common.base.Preconditions.checkState;

import com.google.common.collect.ImmutableList;
import com.google.inject.AbstractModule;
import com.google.inject.Key;

import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;

/**
 * Configures the servlet scopes and creates bindings for the servlet API
 * objects so you can inject the request, response, session, etc.
 *
 * <p>
 * You should subclass this module to register servlets and
 * filters in the {@link #configureServlets()} method.
 *
 * @author [email protected] (Bob Lee)
 * @author [email protected] (Dhanji R. Prasanna)
 */
public class ServletModule extends AbstractModule {

  @Override
  protected final void configure() {
    checkState(filtersModuleBuilder == null, "Re-entry is not allowed.");
    checkState(servletsModuleBuilder == null, "Re-entry is not allowed.");
    filtersModuleBuilder = new FiltersModuleBuilder(binder());
    servletsModuleBuilder = new ServletsModuleBuilder(binder());
    try {
      // Install common bindings (skipped if already installed).
      install(new InternalServletModule());
  
      // Install local filter and servlet bindings.
      configureServlets();
    } finally {
      filtersModuleBuilder = null;
      servletsModuleBuilder = null;
    }
  }

  /**
   * <h3>Servlet Mapping EDSL</h3>
   *
   * <p> 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:
   *
   * <pre>
   *   Guice.createInjector(..., new ServletModule() {
   *
   *     {@literal @}Override
   *     protected void configureServlets() {
   *       <b>serve("*.html").with(MyServlet.class)</b>
   *     }
   *   }
   * </pre>
   *
   * This registers a servlet (subclass of {@code HttpServlet}) called {@code MyServlet} to service
   * any web pages ending in {@code .html}. You can also use a path-style syntax to register
   * servlets:
   *
   * <pre>
   *       <b>serve("/my/*").with(MyServlet.class)</b>
   * </pre>
   *
   * Every servlet (or filter) is required to be a singleton. If you cannot annotate the class
   * directly, you should add a separate {@code bind(..).in(Singleton.class)} rule elsewhere in
   * your module. Mapping a servlet that is bound under any other scope is an error.
   *
   * <p>
   * <h4>Dispatch Order</h4>
   * 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:
   *
   * <pre>
   *
   *   Guice.createInjector(..., new ServletModule() {
   *
   *     {@literal @}Override
   *     protected void configureServlets() {
   *       filter("/*").through(MyFilter.class);
   *       filter("*.css").through(MyCssFilter.class);
   *       filter("*.jpg").through(new MyJpgFilter());
   *       // etc..
   *
   *       serve("*.html").with(MyServlet.class);
   *       serve("/my/*").with(MyServlet.class);
   *       serve("*.jpg").with(new MyServlet());
   *       // etc..
   *      }
   *    }
   * </pre>
   * This will traverse down the list of rules in lexical order. For example, a url
   *  "{@code /my/file.js}" (after it runs through the matching filters) will first
   *  be compared against the servlet mapping:
   * 
   * <pre>
   *       serve("*.html").with(MyServlet.class);
   * </pre>
   * And failing that, it will descend to the next servlet mapping:
   *
   * <pre>
   *       serve("/my/*").with(MyServlet.class);
   * </pre>
   *
   * Since this rule matches, Guice Servlet will dispatch to {@code MyServlet}. These
   * two mapping rules can also be written in more compact form using varargs syntax:
   *
   * <pre>
   *       serve(<b>"*.html", "/my/*"</b>).with(MyServlet.class);
   * </pre>
   * 
   * This way you can map several URI patterns to the same servlet. A similar syntax is
   * also available for filter mappings.
   *
   * <p>
   * <h4>Regular Expressions</h4>
   * You can also map servlets (or filters) to URIs using regular expressions:
   * <pre>
   *    <b>serveRegex("(.)*ajax(.)*").with(MyAjaxServlet.class)</b>
   * </pre>
   *
   * This will map any URI containing the text "ajax" in it to {@code MyAjaxServlet}. Such as:
   * <ul>
   * <li>http://www.google.com/ajax.html</li>
   * <li>http://www.google.com/content/ajax/index</li>
   * <li>http://www.google.com/it/is_totally_ajaxian</li>
   * </ul>
   *
   *
   * <h3>Initialization Parameters</h3>
   *
   * Servlets (and filters) allow you to pass in init params
   * using the {@code <init-param>} tag in web.xml. You can similarly pass in parameters to
   * Servlets and filters registered in Guice-servlet using a {@link java.util.Map} of parameter
   * name/value pairs. For example, to initialize {@code MyServlet} with two parameters
   * ({@code name="Dhanji", site="google.com"}) you could write:
   *
   * <pre>
   *  Map&lt;String, String&gt; params = new HashMap&lt;String, String&gt;();
   *  params.put("name", "Dhanji");
   *  params.put("site", "google.com");
   *
   *  ...
   *      serve("/*").with(MyServlet.class, <b>params</b>)
   * </pre>
   *
   * <p>
   * <h3>Binding Keys</h3>
   *
   * 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:
   *
   * <pre>
   *  ...
   *      filter("/*").through(<b>Key.get(Filter.class, Fave.class)</b>);
   * </pre>
   *
   * Where {@code Filter.class} refers to the Servlet API interface and {@code Fave.class} is a
   * custom binding annotation. Elsewhere (in one of your own modules) you can bind this
   * filter's implementation:
   *
   * <pre>
   *   bind(Filter.class)<b>.annotatedWith(Fave.class)</b>.to(MyFilterImpl.class);
   * </pre>
   *
   * See {@link com.google.inject.Binder} for more information on binding syntax.
   *
   * <p>
   * <h3>Multiple Modules</h3>
   *
   * It is sometimes useful to capture servlet and filter mappings from multiple different
   * modules. This is essential if you want to package and offer drop-in Guice plugins that
   * provide servlet functionality.
   *
   * <p>
   * Guice Servlet allows you to register several instances of {@code ServletModule} to your
   * injector. The order in which these modules are installed determines the dispatch order
   * of filters and the precedence order of servlets. For example, if you had two servlet modules,
   * {@code RpcModule} and {@code WebServiceModule} and they each contained a filter that mapped
   * to the same URI pattern, {@code "/*"}:
   *
   * <p>
   * In {@code RpcModule}:
   * <pre>
   *     filter("/*").through(RpcFilter.class);
   * </pre>
   *
   * In {@code WebServiceModule}:
   * <pre>
   *     filter("/*").through(WebServiceFilter.class);
   * </pre>
   *
   * Then the order in which these filters are dispatched is determined by the order in which
   * the modules are installed:
   *
   * <pre>
   *   <b>install(new WebServiceModule());</b>
   *   install(new RpcModule());
   * </pre>
   *
   * In the case shown above {@code WebServiceFilter} will run first.
   * 
   * @since 2.0
   */
  protected void configureServlets() {
  }


  private FiltersModuleBuilder filtersModuleBuilder;
  private ServletsModuleBuilder servletsModuleBuilder;

  private FiltersModuleBuilder getFiltersModuleBuilder() {
    checkState(filtersModuleBuilder != null,
        "This method can only be used inside configureServlets()");
    return filtersModuleBuilder;
  }

  private ServletsModuleBuilder getServletModuleBuilder() {
    checkState(servletsModuleBuilder != null,
        "This method can only be used inside configureServlets()");
    return servletsModuleBuilder;
  }

  /**
   * @param urlPattern Any Servlet-style pattern. examples: /*, /html/*, *.html, etc.
   * @since 2.0
   */
  protected final FilterKeyBindingBuilder filter(String urlPattern, String... morePatterns) {
    return getFiltersModuleBuilder()
        .filter(ImmutableList.<String>builder().add(urlPattern).add(morePatterns).build());
  }

  /**
   * @param regex Any Java-style regular expression.
   * @since 2.0
   */
  protected final FilterKeyBindingBuilder filterRegex(String regex, String... regexes) {
    return getFiltersModuleBuilder()
        .filterRegex(ImmutableList.<String>builder().add(regex).add(regexes).build());
  }

  /**
   * @param urlPattern Any Servlet-style pattern. examples: /*, /html/*, *.html, etc.
   * @since 2.0
   */
  protected final ServletKeyBindingBuilder serve(String urlPattern, String... morePatterns) {
    return getServletModuleBuilder()
        .serve(ImmutableList.<String>builder().add(urlPattern).add(morePatterns).build());
  }

  /**
   * @param regex Any Java-style regular expression.
   * @since 2.0
   */
  protected final ServletKeyBindingBuilder serveRegex(String regex, String... regexes) {
    return getServletModuleBuilder()
        .serveRegex(ImmutableList.<String>builder().add(regex).add(regexes).build());
  }

  /**
   * This method only works if you are using the {@linkplain GuiceServletContextListener} to
   * create your injector. Otherwise, it returns null.
   * @return The current servlet context.
   * @since 3.0
   */
  protected final ServletContext getServletContext() {
    return GuiceFilter.getServletContext();
  }

  /**
   * See the EDSL examples at {@link ServletModule#configureServlets()}
   *
   * @since 2.0
   */
  public static interface FilterKeyBindingBuilder {
    void through(Class<? extends Filter> filterKey);
    void through(Key<? extends Filter> filterKey);
    /** @since 3.0 */
    void through(Filter filter);
    void through(Class<? extends Filter> filterKey, Map<String, String> initParams);
    void through(Key<? extends Filter> filterKey, Map<String, String> initParams);
    /** @since 3.0 */
    void through(Filter filter, Map<String, String> initParams);
  }

  /**
   * See the EDSL examples at {@link ServletModule#configureServlets()}
   *
   * @since 2.0
   */
  public static interface ServletKeyBindingBuilder {
	 ServletMethodBindingBuilder with(Class<? extends HttpServlet> servletKey);
	 ServletMethodBindingBuilder with(Key<? extends HttpServlet> servletKey);
    /** @since 3.0 */
	 ServletMethodBindingBuilder with(HttpServlet servlet);
	 ServletMethodBindingBuilder with(Class<? extends HttpServlet> servletKey, Map<String, String> initParams);
	 ServletMethodBindingBuilder with(Key<? extends HttpServlet> servletKey, Map<String, String> initParams);
    /** @since 3.0 */
	 ServletMethodBindingBuilder with(HttpServlet servlet, Map<String, String> initParams);
  }
  
  public static interface ServletMethodBindingBuilder {
	  void at(String methodName);
  }
}
/**
 * Copyright (C) 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.inject.servlet;

import static com.google.inject.servlet.ManagedServletPipeline.REQUEST_DISPATCHER_REQUEST;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Iterators;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Scopes;
import com.google.inject.spi.BindingTargetVisitor;
import com.google.inject.spi.ProviderInstanceBinding;
import com.google.inject.spi.ProviderWithExtensionVisitor;

/**
 * An internal representation of a servlet definition mapped to a particular URI pattern. Also
 * performs the request dispatch to that servlet. How nice and OO =)
 *
 * @author [email protected] (Dhanji R. Prasanna)
 */
class ServletDefinition implements ProviderWithExtensionVisitor<ServletDefinition> {
  private final String pattern;
  private final Key<? extends HttpServlet> servletKey;
  private final UriPatternMatcher patternMatcher;
  private final Map<String, String> initParams;
  // set only if this was bound using a servlet instance.
  private final HttpServlet servletInstance;
  private final String methodName;
  //always set in init, our servlet is always presumed to be a singleton
  private final AtomicReference<HttpServlet> httpServlet = new AtomicReference<HttpServlet>();

  public ServletDefinition(String pattern, Key<? extends HttpServlet> servletKey,
      UriPatternMatcher patternMatcher, Map<String, String> initParams, HttpServlet servletInstance, String methodName) {
    this.pattern = pattern;
    this.servletKey = servletKey;
    this.patternMatcher = patternMatcher;
    this.initParams = Collections.unmodifiableMap(new HashMap<String, String>(initParams));
    this.servletInstance = servletInstance;
    this.methodName = methodName;
  }

  public ServletDefinition get() {
    return this;
  }

  public <B, V> V acceptExtensionVisitor(BindingTargetVisitor<B, V> visitor,
      ProviderInstanceBinding<? extends B> binding) {
    if(visitor instanceof ServletModuleTargetVisitor) {
      if(servletInstance != null) {
        return ((ServletModuleTargetVisitor<B, V>)visitor).visit(
            new InstanceServletBindingImpl(initParams,
                pattern,
                servletInstance,
                patternMatcher));
      } else {
        return ((ServletModuleTargetVisitor<B, V>)visitor).visit(
            new LinkedServletBindingImpl(initParams,
                pattern,
                servletKey,
                patternMatcher));
      }
    } else {
      return visitor.visit(binding);
    }
  }

  boolean shouldServe(String uri) {
    return uri != null && patternMatcher.matches(uri);
  }

  public void init(final ServletContext servletContext, Injector injector,
      Set<HttpServlet> initializedSoFar) throws ServletException {

    // This absolutely must be a singleton, and so is only initialized once.
    if (!Scopes.isSingleton(injector.getBinding(servletKey))) {
      throw new ServletException("Servlets must be bound as singletons. "
        + servletKey + " was not bound in singleton scope.");
    }

    HttpServlet httpServlet = injector.getInstance(servletKey);
    this.httpServlet.set(httpServlet);

    // Only fire init() if we have not appeared before in the filter chain.
    if (initializedSoFar.contains(httpServlet)) {
      return;
    }

    //initialize our servlet with the configured context params and servlet context
    httpServlet.init(new ServletConfig() {
      public String getServletName() {
        return servletKey.toString();
      }

      public ServletContext getServletContext() {
        return servletContext;
      }

      public String getInitParameter(String s) {
        return initParams.get(s);
      }

      public Enumeration getInitParameterNames() {
        return Iterators.asEnumeration(initParams.keySet().iterator());
      }
    });

    // Mark as initialized.
    initializedSoFar.add(httpServlet);
  }

  public void destroy(Set<HttpServlet> destroyedSoFar) {
    HttpServlet reference = httpServlet.get();

    // Do nothing if this Servlet was invalid (usually due to not being scoped
    // properly). According to Servlet Spec: it is "out of service", and does not
    // need to be destroyed.
    // Also prevent duplicate destroys to the same singleton that may appear
    // more than once on the filter chain.
    if (null == reference || destroyedSoFar.contains(reference)) {
      return;
    }

    try {
      reference.destroy();
    } finally {
      destroyedSoFar.add(reference);
    }
  }

  /**
   * Wrapper around the service chain to ensure a servlet is servicing what it must and provides it
   * with a wrapped request.
   *
   * @return Returns true if this servlet triggered for the given request. Or false if
   *          guice-servlet should continue dispatching down the servlet pipeline.
   *
   * @throws IOException If thrown by underlying servlet
   * @throws ServletException If thrown by underlying servlet
   */
  public boolean service(ServletRequest servletRequest,
      ServletResponse servletResponse) throws IOException, ServletException {

    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final String path = ServletUtils.getContextRelativePath(request);

    final boolean serve = shouldServe(path);

    //invocations of the chain end at the first matched servlet
    if (serve) {
      doService(servletRequest, servletResponse);
    }

    //return false if no servlet matched (so we can proceed down to the web.xml servlets)
    return serve;
  }

  /**
   * Utility that delegates to the actual service method of the servlet wrapped with a contextual
   * request (i.e. with correctly computed path info).
   *
   * We need to suppress deprecation coz we use HttpServletRequestWrapper, which implements
   * deprecated API for backwards compatibility.
   */
  void doService(final ServletRequest servletRequest, ServletResponse servletResponse)
      throws ServletException, IOException {

    HttpServletRequest request = new HttpServletRequestWrapper(
        (HttpServletRequest) servletRequest) {
      private boolean pathComputed;
      private String path;

      private boolean pathInfoComputed;
      private String pathInfo;

      @Override
      public String getPathInfo() {
        if (!isPathInfoComputed()) {
          int servletPathLength = getServletPath().length();
          pathInfo = getRequestURI().substring(getContextPath().length())
              .replaceAll("[/]{2,}", "/");
          pathInfo = pathInfo.length() > servletPathLength
              ? pathInfo.substring(servletPathLength) : null;

          // Corner case: when servlet path and request path match exactly (without trailing '/'),
          // then pathinfo is null
          if ("".equals(pathInfo) && servletPathLength != 0) {
            pathInfo = null;
          }

          pathInfoComputed = true;
        }

        return pathInfo;
      }

      // NOTE(dhanji): These two are a bit of a hack to help ensure that request dispatcher-sent
      // requests don't use the same path info that was memoized for the original request.
      // NOTE(iqshum): I don't think this is possible, since the dispatcher-sent request would
      // perform its own wrapping.
      private boolean isPathInfoComputed() {
        return pathInfoComputed
            && !(null != servletRequest.getAttribute(REQUEST_DISPATCHER_REQUEST));
      }

      private boolean isPathComputed() {
        return pathComputed
            && !(null != servletRequest.getAttribute(REQUEST_DISPATCHER_REQUEST));
      }

      @Override
      public String getServletPath() {
        return computePath();
      }

      @Override
      public String getPathTranslated() {
        final String info = getPathInfo();

        return (null == info) ? null : getRealPath(info);
      }

      // Memoizer pattern.
      private String computePath() {
        if (!isPathComputed()) {
          String servletPath = super.getServletPath();
          path = patternMatcher.extractPath(servletPath);
          pathComputed = true;

          if (null == path) {
            path = servletPath;
          }
        }

        return path;
      }
    };

    doServiceImpl(request, (HttpServletResponse) servletResponse);
  }

  private void doServiceImpl(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    GuiceFilter.Context previous = GuiceFilter.localContext.get();
    HttpServletRequest originalRequest
        = (previous != null) ? previous.getOriginalRequest() : request;
    GuiceFilter.localContext.set(new GuiceFilter.Context(originalRequest, request, response));
    try {
    	HttpServlet reference = httpServlet.get();
    	Method method = reference.getClass().getDeclaredMethod(this.methodName, HttpServletRequest.class, HttpServletResponse.class);
    	method.invoke(reference, request, response);
    } catch (SecurityException e) {
		throw new ServletException(e);
	} catch (NoSuchMethodException e) {
		throw new ServletException(e);
	} catch (IllegalArgumentException e) {
		throw new ServletException(e);
	} catch (IllegalAccessException e) {
		throw new ServletException(e);
	} catch (InvocationTargetException e) {
		throw new ServletException(e);
	} finally {
      GuiceFilter.localContext.set(previous);
    }
  }

  String getKey() {
    return servletKey.toString();
  }

  String getPattern() {
    return pattern;
  }
}

Reply via email to