Java 如何在简单的类文件中获取 ServletContext 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2728877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i get ServletContext object in a simple class file?
提问by TCM
I am creating a simple web application. I need to get reference to ServletContext object in that class. How can i get it?
我正在创建一个简单的 Web 应用程序。我需要在该类中获取对 ServletContext 对象的引用。我怎么才能得到它?
采纳答案by Bozho
You'd better pass it as argument to the constructor of your object, or set it using a setter method.
您最好将它作为参数传递给对象的构造函数,或者使用 setter 方法设置它。
In fact, you may obtain the context attribute that is relevant to your object and pass only it via constructor/setter. For example:
事实上,您可以获得与您的对象相关的上下文属性,并仅通过构造函数/setter 传递它。例如:
YourClass obj =
new YourClass((AnotherClass) servletContext.getAttribute("yourAttribute"));
A much worse and more complication option is to:
一个更糟糕、更复杂的选择是:
- 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.
- 创建一个
ServletContextListener
- 在 web.xml 中注册它
<listener><listener-class></listener-class></listener>
- 在
contextInitialized(..)
得到ServletContext
从事件并将其存储在一个单-静态字段somehwere。
Alternatively, you can do this on each request, using a ServletRequestListener
and store it in a ThreadLocal
instead.
或者,您可以对每个请求执行此操作,使用 aServletRequestListener
并将其存储在 a 中ThreadLocal
。
Then you can obtain the value via calling your singleton/threadlocal holder like this:
然后你可以通过像这样调用你的单例/线程本地持有者来获取值:
ServletContextHolder.getCurrentServletContext()
回答by Ted Cahall
I had this issue, but since I had called the class from a JSP, I simply passed the HttpServletRequest "request" reference from the JSP to the class and made the call in the class to:
我遇到了这个问题,但是由于我从 JSP 调用了该类,所以我只是将 HttpServletRequest “请求”引用从 JSP 传递给了该类,并在该类中进行了调用:
String appPath = request.getServletContext().getRealPath("");