开发者

How do I filter all incoming requests and not just ones mapped to servlets?

I am toying around with embedded Jetty and I am wondering why my filter only intercepts /hi and not any other incoming request. Here is my example case:

Without Filter:

lo开发者_开发问答calhost:8080/hi
=> "Hello"
localhost:8080/foo
=> 404

With Filter:

localhost:8080/hi
=> "Hello from filter"
localhost:8080/foo
=> 404

I would expect the last 404 to return "Hello from filter". What am I missing?

Server server=new Server(8080);

ServletContextHandler context=
    new ServletContextHandler(ServletContextHandler.SESSIONS);

context.setContextPath("/");
context.addFilter(DispatchFilter.class,"/*",1);
context.addServlet(HelloServlet.class,"/hi");

server.setHandler(context);
server.start();
server.join();

To further clarify, my example is just a simplified representation of what I want to do. My intention is to have the DispatchFilter intercept every request. If a certain criteria is not met, then it should move on, otherwise return something derived from the request path.


From javax.servlet.Filter.doFilter()

The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.

The key part here is the bit about the "end of the chain". Since /foo doesn't match an actual resource, the filters are not executed.

You can work around this by adding a default servlet:

context.addServlet(org.mortbay.jetty.servlet.DefaultServlet, "/");

Now all your requests have a valid endpoint and your filter will be executed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜