Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet Filter vs. ServletRequestListener

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?

like image 576
deamon Avatar asked Dec 28 '09 16:12

deamon


1 Answers

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.

like image 80
Dan Avatar answered Oct 12 '22 00:10

Dan