Hello, I am creating a simple web application. I need to get reference to ServletContext object in that class. How can i get it?
+6
A:
You'd better pass it as argument to the constructor of your object, or set it using a setter method.
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:
- Create a
ServletContextListener
- register it in web.xml with `
- on
contextInitialized(..)
get theServletContext
from the event and store it in a singleton - a static field somehwere.
Alternatively, you can do this on each request, using a ServletRequestListener
and store it in a ThreadLocal
instead.
Then you can obtain the value via calling your singleton/treadlocal holder like this:
ServletContextHolder.getCurrentServletContext()
Bozho
2010-04-28 11:17:31
Or pass into a constructor a copy/view of `ServletContext` relevant to the object in question.
Tom Hawtin - tackline
2010-04-28 11:25:54
@Tom: that's already mentioned in the first sentence.
BalusC
2010-04-28 11:32:19
maybe Tom meant that you should obtain the context attribute that is relevant to the object and pass only it. I'll include it.
Bozho
2010-04-28 11:35:41
Great Answer Bozho!
Ankit Rathod
2010-04-28 11:56:52
@BalusC I mean the relevant pieces from `ServletContext`, not the whole thing. It is a design error for a "simple class" to know about the servlets.
Tom Hawtin - tackline
2010-04-28 13:10:08