有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java向guice servlet添加过滤器

我使用guice servet创建了一个servlet,效果很好:

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

我的servlet如下所示:

@Inject
private MyService myService;

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

现在,我尝试向它添加一个过滤器,就像这样:

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

我的过滤器如下所示:

@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() { }
}

一旦我添加了过滤器,servlet就不再被调用

当我移除过滤器时,servlet再次工作

我做错了什么


共 (1) 个答案

  1. # 1 楼答案

    问题不在Guice程序集中,而是在过滤器实现中。你必须打电话:

    chain.doFilter(request, response);
    

    doFilter方法中,通过过滤器传递处理。您可以在javadoc中阅读有关典型过滤器的更多信息