Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the context without any request, session, etc?

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.

like image 624
peterh Avatar asked Oct 31 '14 08:10

peterh


People also ask

What is request getServletContext ()?

getServletContext() method of ServletConfig interface returns the object of ServletContext. getServletContext() method of GenericServlet class returns the object of ServletContext.

Which of the following is the correct way to get servlet context object?

ServletConfig object is obtained by getServletConfig() method. ServletContext object is obtained by getServletContext() method. Each servlet has got its own ServletConfig object.

What is getServletContext in Java?

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.

What is the difference between session and request?

Session attributes are meant for contextual information, such as user identification. Request attributes are meant for specific request info, such as query results.


1 Answers

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.

like image 171
icza Avatar answered Nov 06 '22 15:11

icza