javapenguin
javapenguin

Reputation: 1046

Adding filter to guice servlet

I created a servlet using guice servet which works fine:

protected Injector getInjector() {
    return Guice.createInjector(new ServletModule() {
        protected void configureServlets() {
            bind(MyService.class).to(MyServiceImpl.class);
            serve("/myservlet").with(MyServlet.class);
        }
    });
}

My servlet looks like this:

@Inject
private MyService myService;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.getWriter().print(myService.hello("John Doe").toString());
}

Now I am trying to add a filter to it like thing:

            bind(MyService.class).to(MyServiceImpl.class);
            filter("/*").through(MyFilter.class);
            serve("/myservlet").with(MyServlet.class);

My filter looks like this:

@Singleton public class MyFilter implements Filter { 
    public void init(FilterConfig filterConfig) throws ServletException { } 
    public void doFilter(ServletRequest request, 
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        System.out.println("Yeah"); 
    } 
    public void destroy() { }
}

As soon as I add the filter the servlet does not get called any more.

When I remove the filter the servlet works again.

What am I doing wrong?

Upvotes: 2

Views: 2803

Answers (1)

Per Huss
Per Huss

Reputation: 5105

The problem is not within you Guice assembly, but with your filter implementation. You will have to call:

chain.doFilter(request, response);

in your doFilter method to pass on the processing through the filter. You can read more about a typical filter in the javadoc.

Upvotes: 2

Related Questions