tags:

views:

129

answers:

1

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:

  1. Create a ServletContextListener
  2. register it in web.xml with `
  3. on contextInitialized(..) get the ServletContext 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
Or pass into a constructor a copy/view of `ServletContext` relevant to the object in question.
Tom Hawtin - tackline
@Tom: that's already mentioned in the first sentence.
BalusC
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
Great Answer Bozho!
Ankit Rathod
@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