jetty / jetty.project

Eclipse Jetty® - Web Container & Clients - supports HTTP/2, HTTP/1.1, HTTP/1.0, websocket, servlets, and more
https://eclipse.dev/jetty
Other
3.87k stars 1.91k forks source link

How to register WebFilters whose urlPatterns have been set in annotation ? #12566

Open zcattacz opened 2 days ago

zcattacz commented 2 days ago

Jetty Version Jetty 12

Jetty Environment

ee10

Java Version JDK17

Question I am embedding Jetty 12 into a existing standard spring 6 project, which has been developed and run under tomcat. The login filter is created with annotation:

@WebFilter(urlPatterns = {"url1", "url2", "url3", ...})
class AuthFilter implements Fitler {... }

This was automatically registered in Tomcat10. so I never thought of how these can be manually added to a ServletContext. With jetty, the examples I can are like below:

~~ Pattern 1
server.addFitler(AuthFilter.class, "url1", null);
~~ Pattern 2
var fh = FilterHolder(AuthFilter.class)
var fm = FilterMapping("url1");
server.addFitler(fh, fm);

I have tried server.addFitler(AuthFilter.class, null, null); without success. I can confirm the filter init() is executed, but url patterns configured in annotation are not triggered. I have also server.addFitler(AuthFilter.class, "/", null); which is triggered for every request.

I wonder if there is any way to register a @WebFitler annotated filter class with url patterns already set in annotation, without specifying its pattern again in addFitler call?

janbartel commented 15 hours ago

@zcattacz you can use the standard servlet api annotations to register your servlets, filters and listeners with jetty too. Just make sure that you have enabled the ee10-annotations module.

If you actually do want to switch to using embedded setup rather than via annotations have a look at https://jetty.org/docs/jetty/12/programming-guide/server/http.html#handler-use-servlet. There's some examples to show you how to define servlets/filters etc and add them to your ServletContextHandler/WebAppContext.