简体   繁体   English

Servlet过滤器与ServletRequestListener

[英]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. 我想将JPA EntityManager绑定到每个请求的当前线程(通过ThreadLocal),可以通过ServletRequestListener或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? 我应该使用Servlet过滤器还是ServletRequestListener来做到这一点?

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. 例如,Spring使用ServletRequestListener来允许不使用Spring自己的Web MVC框架的Spring基于Web的应用程序访问特定于Web的功能,例如会话范围的bean。 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. 编辑:为了更清楚,我提到了Spring的RequestContextListener,因为它完全符合你所说的:创建一个ThreadLocal对象来存储可以在整个请求生命周期的整个过程中访问的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM