0

At many places in my web application I need a certain String which is :

request.getServletContext().getRealPath("/"); 
// I can only get this once the web-app starts

Sometimes a simple java class needs to know this string. I don't want to pass each and every time this string to the class's function. One way could be to stash this string in a file at the very beginning of the web application. Every time I would need this, simply read the file.But this doesn't seem a pretty good option. Is there any other way out ?

May be I can store in the context.xml of the application. If it is possible how do I do that ?

If there is a better way please suggest.

I am using tomcat as the server.

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • Get the string at the beginning of your application (initialisation of the class) and then store it as a static variable of the class until the end of the program? – Ozzy Feb 03 '13 at 14:23

2 Answers2

1

Invoke run the following code when your application starts (e.g. with a ServletContextListener):

public void contextInitialized(ServletContextEvent sce) {
   ServletContextRootRealPath.set(sce.getServletContext().getRealPath("/"));
}

Then later whenever you need it you simply call

ServletContextRootRealPath.get()

Since it's all static the variable is accessible JVM-wide to every code that runs in this JVM.

Utility class

public final class ServletContextRootRealPath {
  private static String path;

  private ServletContextRootRealPath() {
    // don't instantiate utility classes
  }

  public static void set(String rootRealPath) {
    path = rootRealPath;
  }

  public static String get() {
    return path;
  }
}
Marcel Stör
  • 22,695
  • 19
  • 92
  • 198
  • Is there a way to put this information inside the `context.xml` ? – Suhail Gupta Feb 03 '13 at 16:25
  • 1
    @SuhailGupta, if you know how to write to a file with Java - sure. What's the point, though? It's way more complicated and less efficient to read the value from the file than to read it from memory with a static variable. – Marcel Stör Feb 03 '13 at 16:36
0

You can store the value in static variable of any class (Basically a helper class which is used for serving common utility functions). Later you can refer to this variable without creating instance of the class, as it is static and can be accessed without its instance.

CuriousMind
  • 3,143
  • 3
  • 29
  • 54
  • But I guess if class `A` sets a static variable in `B` then class `C` cannot access that variable until it sets its own.It is between the two processes. – Suhail Gupta Feb 03 '13 at 15:56
  • Its a static variable and it has nothing to do with instances and who is setting it. And when you say two processes? does that mean two separate JVMs? – CuriousMind Feb 03 '13 at 17:12
  • Aaah ! I actually meant two separate JVMs but didn't realize it. Anyways thank you. – Suhail Gupta Feb 03 '13 at 18:08