问题描述
我正在创建一个简单的Web应用程序.我需要在该类中获取对ServletContext对象的引用.我怎么能得到它?
I am creating a simple web application. I need to get reference to ServletContext object in that class. How can i get it?
推荐答案
最好将其作为参数传递给对象的构造函数,或使用setter方法进行设置.
You'd better pass it as argument to the constructor of your object, or set it using a setter method.
实际上,您可以获取与对象相关的context属性,并仅通过构造函数/setter传递它.例如:
In fact, you may obtain the context attribute that is relevant to your object and pass only it via constructor/setter. For example:
YourClass obj =
new YourClass((AnotherClass) servletContext.getAttribute("yourAttribute"));
更糟糕,更复杂的选择是:
A much worse and more complication option is to:
- 创建一个
ServletContextListener
- 使用
< listener>< listener-class></listener-class></listener>
在web.xml中注册 - 在
contextInitialized(..)
上从事件中获取ServletContext
并将其存储在单个实例中-某个静态字段.
- Create a
ServletContextListener
- register it in web.xml with
<listener><listener-class></listener-class></listener>
- on
contextInitialized(..)
get theServletContext
from the event and store it in a singleton - a static field somehwere.
或者,您可以使用 ServletRequestListener
对每个请求执行此操作,并将其存储在 ThreadLocal
中.
Alternatively, you can do this on each request, using a ServletRequestListener
and store it in a ThreadLocal
instead.
然后您可以通过调用单例/threadlocal持有者来获取值,如下所示:
Then you can obtain the value via calling your singleton/threadlocal holder like this:
ServletContextHolder.getCurrentServletContext()
这篇关于如何在简单的类文件中获取ServletContext对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!