我正在尝试遵循关于在web服务器上使用Guice的最小教程,而不需要web.xml:http://www.remmelt.com/post/minimal-guice-servlet-without-web-xml/
像本教程的创建者一样,我不能设法使WebFilter命令按预期工作,但是所有相同的代码,而不是使用filter类上的@ ServletModule属性会产生一个正常工作的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!“。
使用过滤器(“/*”),我在相同的请求上得到了404。
发布于 2019-07-03 10:26:10
据我所知,我要找的东西是不可能的。为了在没有@WebFilter属性的情况下声明筛选器,您必须有一个如下所示的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,为了更容易的配置,没有办法避免这两种情况。
https://stackoverflow.com/questions/56845478
复制相似问题