Can java / scala / etc code indicate when tomcat is running?

I have data for my webapp in a database that is accessed differently from different places. There is no generic code that can simply do this for both. Therefore, I want to know at runtime that I am in. In fact, the code to run really depends on whether it runs inside or without tomcat, so I would like to detect this at runtime. How to do it?

+3
source share
6 answers

I agree with kbrasee that this is not a good situation to be, so if you could, I would choose it if possible.

However, if you have no choice and need to do this, they do so in the implementation of Liferay. Take a look at the ServerDetector class

In the _dectect method (below), you will notice that they are looking for the class that they defined, is present if it is running on this server. They define classes at the top in the constants TOMCAT_BOOTSTRAP_CLASS and TOMCAT_EMBEDDED_CLASS.

We had a problem finding the built-in tomcat inside the glass fish. I'm not sure if this is fixed in the version I am associated with, but this may not be a problem for you.

+2
source

, . - , . - -, ( , , , ). - , -- .

- , - , , System ( , -D ), , . , -, --.

+3

, , $0,02 .

, ServerDetector , , : , , , , ? . , , , - .

Scala:

def inTomcat: Boolean = (new Throwable).getStackTrace.exists(_.getClassName.startsWith("org.apache.catalina"))
+2

, , , , , , API, . OSGi , JVM .

, , Tomcat , - , JNDI. , , , Tomcat.

0

, , dev CLI Tomcat, , .

I use this java function

public static boolean _amServer() {
  StackTraceElement[] elements = new Throwable().getStackTrace();

  for (StackTraceElement element : elements) {
    if (element.getClassName().equals("org.apache.catalina.core.StandardEngineValve")) {
      return true;
    }
  }

  return false;
}
0
source

I found the following solution simple and straightforward ( taken from another q & a ):

String path = getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
boolean insideWarFile = path.contains("WEB-INF");
0
source

Source: https://habr.com/ru/post/1719570/


All Articles