Chitresh
Chitresh

Reputation: 3092

How to start and stop tomcat using java code?

How to start and stop tomcat using java code?

Upvotes: 9

Views: 29679

Answers (5)

Am Anonymous
Am Anonymous

Reputation: 79

For Linux Users using java, try this:

Runtime run = Runtime.getRuntime();
Process pr = run.exec("sh startup.sh", null, new File("filePath"));
filePathexample = /home/example/apache-tomcat-8.0.47/bin/

Upvotes: 0

Michal
Michal

Reputation: 2423

Start (and stop) an embedded Tomcat. It is well documented how to do this, for example here.

Upvotes: 0

Cloud
Cloud

Reputation: 993

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(); 
}

Upvotes: 17

mindas
mindas

Reputation: 26713

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.

Upvotes: 15

Jigar Joshi
Jigar Joshi

Reputation: 240900

You can execute native commands using java

String command = "c:\program files\tomcat\bin\startup.bat";//for linux use .sh
Process child = Runtime.getRuntime().exec(command);

Upvotes: 9

Related Questions