Evgeny
Evgeny

Reputation: 2161

How to shutdown a single application in Tomcat?

I would like to run some code, in my webapplication, to cause the application to stop. For example, if the database server is unavailable. I would like to implement something like App.exit() similar to System.exit().

FYI

The answer in "Shutdown tomcat using web application deployed in it" is about shutting down the whole container. The question here is about shutting down (or temporary disabling) a single web application.

Upvotes: 5

Views: 4270

Answers (2)

Stefan
Stefan

Reputation: 12462

You can shutdown a single application in Tomcat, using MBeans/JMX:

public void shutdownApp() {
    try {
        String serviceName = "Catalina"; // @see server.xml
        String hostName = "localhost"; // @see server.xml
        String contextName = "MyApplicationName"; // the name of your application in the URL

        Hashtable<String, String> keys = new Hashtable<>();
        keys.put("j2eeType", "WebModule");
        keys.put("name", "//" + hostName + "/" + contextName);
        keys.put("J2EEApplication", "none");
        keys.put("J2EEServer", "none");

        MBeanServerConnection mbeanServer = ManagementFactory.getPlatformMBeanServer();
        ObjectName appObject = ObjectName.getInstance(serviceName, keys);
        System.out.println("Found objectName: " + appObject);
        mbeanServer.invoke(appObject, "stop", null, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The serviceName, hostName and contextName vars need to be changed according to your configuration. This example will shutdown an app that is deployed like this:

hxxp://localhost:8080/MyApplicationName

Beside "stop" you may also call: "start" or "reload".

Upvotes: 6

vels4j
vels4j

Reputation: 11298

Usually we dont call App.exit or System.exit in a web application. If Database server is not avilable only the reason or kind of similar issue you can do the following

  1. Write a ContextListner implmenting ServletContextListener
  2. On contextInitialized method check necessary application init configurations like set up DB connections, default configuration etc.,
  3. Incase any errors in context initilzation, keep your servlet and jsp pages informed that application is not ready and redirect to error page.

Also using tomcat manager you can start/stop/deploy any webapps in your tomcat container.

Upvotes: 1

Related Questions