title: Java / Jetty: How to Add Filter to Embedded Jetty
body: <p>I am working with embedded Jetty and I want to add a servlet filter to check for authentication before each request.  I tried following <a href="http://permalink.gmane.org/gmane.comp.java.jetty.support/14273">this example</a> but it looks like the signature has changed.</p>
  
  <pre><code>&lt;dependency&gt;
      &lt;groupId&gt;org.eclipse.jetty&lt;/groupId&gt;
      &lt;artifactId&gt;jetty-server&lt;/artifactId&gt;
      &lt;version&gt;9.0.4.v20130625&lt;/version&gt;
  &lt;/dependency&gt;
  </code></pre>
  
  <p>My Jetty starter looks like this:</p>
  
  <pre><code>public class JettyStarter {
  
      public static void main( final String[] args ) throws Exception {
          Server server = new Server(8080);
          final ServletHolder servletHolder = new ServletHolder(new CXFServlet());
          final ServletContextHandler context = new ServletContextHandler();
          context.setContextPath("/");
          // context.addFilter(AuthenticationFilter.class, "/*", FilterMapping.REQUEST);
          context.addServlet(servletHolder, "/platform/*");
          context.addEventListener(new ContextLoaderListener());
          context.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
          context.setInitParameter("contextConfigLocation", Config.class.getName());
          server.setHandler(context);
          server.start();
          server.join();
      }
  }
  </code></pre>
  
  <p>When I uncomment the line </p>
  
  <pre><code>// context.addFilter(AuthenticationFilter.class, "/*", FilterMapping.REQUEST);
  </code></pre>
  
  <p>I find that the signature has changed.   So I want to take a small step back and ask, with embedded Jetty, how do I add a filter that runs at the beginning of the request and allows the request to continue only if some condition is met? </p>
  
  <p>The beginning of the AuthenticationFilter class looks like this:</p>
  
  <pre><code>import javax.servlet.*;
  import java.io.IOException;
  
  public class AuthenticationFilter implements Filter {
  
      @Override
      public void init(FilterConfig filterConfig) throws ServletException {}
  
      @Override
      public void doFilter(ServletRequest servletRequest, 
                           ServletResponse servletResponse, 
                           FilterChain filterChain) throws IOException, ServletException {}
  
      @Override
      public void destroy() {}
  
  }
  </code></pre>