我正在尝试关于在Web服务器上使用Guice的最小指导,而不需要web.xml:http://www.remmelt.com/post/minimal-guice-servlet-without-web-xml/
就像本教程的创建者一样,我无法设法使ServletModule过滤器命令按预期方式工作,但是所有相同的代码,而是使用Filter类上的@WebFilter属性可以使Web服务器正常工作。
如何使ServletModule过滤器起作用? ServletModule的filter方法和@WebFilter属性有什么不同,导致期望值出现这种差异?
除了本教程介绍的内容之外,我还尝试在“ filter”命令之前绑定过滤器。
@WebListener
public class GuiceServletConfig extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(new ServletModule() {
@Override
protected void configureServlets() {
super.configureServlets();
serve("/*").with(WiredServlet.class);
filter("/*").through(GuiceWebFilter.class);
bind(MessageSender.class).to(MessageSenderImpl.class);
}
});
}
}
public class GuiceWebFilter extends GuiceFilter{
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
super.doFilter(servletRequest, servletResponse, filterChain);
}
}
@Singleton
public class WiredServlet extends HttpServlet {
@Inject
private MessageSender messageSender;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getOutputStream().print("Hello world!");
}
}
使用@WebFilter(“ / *”),我得到一个简单的响应“ Hello World!”。
使用filter(“ / *”),我在同一请求上得到了404。
答案 0 :(得分:0)
据我所知,我要找的东西是不可能的。为了声明没有@WebFilter属性的Filter,您必须具有以下web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Application</display-name>
<filter>
<filter-name>guiceFilter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>guiceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
因此,总而言之,您可以使用@WebFilter属性,或者必须具有web.xml,为了更易于阅读的配置,无法避免两者。