How to start and stop tomcat using java code?
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();
}
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.
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);