I want to bind a JPA EntityManager to the current thread on each request (via ThreadLocal), what could be done via a ServletRequestListener or Filter. The listener looks cleaner and I don't need the additional possibilities of a filter in this case. But maybe the filter has an advantage I've missed.
Should I use a Servlet Filter or a ServletRequestListener to do that?
For your purpose there's not much difference. But a listener is "cleaner" in the sense that someone reading your code will immediately know that the purpose of this code can't possibly be to intercept the request or alter it or do other things that a filter can do.
Spring, for example, uses a ServletRequestListener to allow Spring web-based apps that are not using Spring's own Web MVC framework to nonetheless get access to web-specific functionality such as session-scoped beans. See this doc.
Edit: just to be more clear, I mention Spring's RequestContextListener because it does exactly what you're talking about: create a ThreadLocal object to store data that can be accessed throughout the rest of the request lifecycle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With