Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start and stop tomcat using java code?

Tags:

java

tomcat

How to start and stop tomcat using java code?

like image 975
Chitresh Avatar asked Mar 10 '11 05:03

Chitresh


2 Answers

You can send the shutdown command to the shutdown port both of which are can be configured in the root element of server.xml file of Tomcat.

By steps:

Step 1

Configure the CATALINA_HOME/conf/server.xml as follow:

<Server port="8005" shutdown="myShutDownCommand">

The attribute port is optional. If it is omitted, the default one, 8005, is used.

The value for shutdown attribute can be anything. This should not be known by others.

Step 2

Make the java program send the shutdown command, myShutDownCommand, using java.net.Socket class to the shutdown port, 8005.

try { 
    Socket socket = new Socket("localhost", 8005); 
    if (socket.isConnected()) { 
        PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); 
        pw.println("myShutDownCommand");//send shut down command 
        pw.close(); 
        socket.close(); 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
}
like image 69
Cloud Avatar answered Nov 02 '22 23:11

Cloud


You need to execute main method of org.apache.catalina.startup.Bootstrap with the parameter "start".

You also need following things:

  • to have tomcat/bin/bootstrap.jar in your classpath;
  • -Dcatalina.base to point to $TOMCAT_HOME
  • -Dcatalina.home to point to $TOMCAT_HOME
  • -Djava.io.tmpdir to point to a temporary directory (usually $TOMCAT_HOME/temp)

I also have -noverify parameter set, not sure if it is always necessary.

p.s. it would also be nice if you could start accepting answers, your current rate is 0/28.

like image 23
mindas Avatar answered Nov 02 '22 23:11

mindas