How to distinguish between a web application or a standalone application.?

Is there a way to distinguish inside a specific method if it is running in a web application (for example, all applications are deployed in the tomcat / web sphere, etc.) or as a separate application?

+3
source share
5 answers

The answer is NO. It is not possible to determine whether your code will work in any application server container / servlet or autonomously without relying on external information.

However, you can specify a system property in one case and not another, and verify its existence:

java -Dstandalone.mode=true MyApplication

In your code:

if (Boolean.getBoolean("standalone.mode")) {
  // we're in standalone mode
}
+2
source

, - HttpServlet . , , .

: . .

public boolean isWebApplication() {
    Class<?> httpServletClass;
    try {
        httpServletClass = Class.forName("javax.servlet.http.HttpServlet");
    } catch (ClassNotFoundException e) {
        return false;
    }

    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace()

    for (StackTraceElement element : stackTrace) {
        Class<?> elementClass = Class.forName(element.getClassName());
        if (httpServletClass.isAssignableFrom(elementClass)) {
            return true;
        }
    }

    return false;
}
+1

, "" -, , J2EE-API , .. HttpServlet. , Class.forName() J2EE app-server-sepcific . , , , , .

+1

, , "", , .

org.apache.catalina.util.ServerInfo.getServerBuilt()

, Tomcat. -, , . -, .

0

, JNDI ( , - , , localhost).

0

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


All Articles