I have a method in a class, which doesn't get anything which could be usable to get the actual servlet context. Practically, it is like
public String getSomething() { ... }
But to calculate the result, I need the actual, thread-specific servlet structures.
I think, somewhere in the deepness in the application context, some like a thread-specific storage should exist, which could be reached by calling static methods of some system class.
I am in a tomcat6 servlet container, but Spring is also available if it is needed.
getServletContext() method of ServletConfig interface returns the object of ServletContext. getServletContext() method of GenericServlet class returns the object of ServletContext.
ServletConfig object is obtained by getServletConfig() method. ServletContext object is obtained by getServletContext() method. Each servlet has got its own ServletConfig object.
Interface ServletContext. public interface ServletContext. Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.
Session attributes are meant for contextual information, such as user identification. Request attributes are meant for specific request info, such as query results.
Add a ServletContextListener
to your web.xml
. This will be called when your webapp is loaded. In the contextInitialized()
method you can store the ServletContext
in a static variable for example for later use. Then you will be able to access the ServletContext
in a static way:
class MyListener implements ServletContextListener {
public static ServletContext context;
@Override
public void contextInitialized(ServletContextEvent sce) {
context = sce.getServletContext();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
context = null;
}
}
Add it to web-xml
like this:
<web-app>
<listener>
<listener-class>
com.something.MyListener
</listener-class>
</listener>
</web-app>
And you can access it from anywhere like this:
public String getSomething() {
// Here you have the context:
ServletContext c = MyListener.context;
}
Note:
You might want to store it as private
and provide a getter
method, and also check for null
value before using it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With