Home > Java > javaTutorial > How to start and shut down Tomcat server using Java?

How to start and shut down Tomcat server using Java?

PHPz
Release: 2023-04-26 10:19:07
forward
1571 people have browsed it

1.项目结构

How to start and shut down Tomcat server using Java?

2.calltomcat.java

package com.calltomcat.test;
import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstreamreader;
public class calltomcat {
 public static void main(string[] args) {
 //string command = "e:\\apache-tomcat-7.0.76\\bin\\startup.bat";//启动tomcat命令
 //string command = "e:\\apache-tomcat-7.0.76\\bin\\tomcat7w.exe";//启动tomcat命令,仅限windows版本,无弹框
 string command = "e:\\apache-tomcat-7.0.76\\bin\\shutdown.bat";//关闭tomcat命令
 calltomcat calltomcat = new calltomcat();
 try {
  calltomcat.callcommand(command);
 } catch (ioexception e) {
  system.out.println("执行命令时出错:" + e.getmessage());
 }
 }
 /**
 * 执行命令
 * 
 * @throws ioexception
 */
 private void callcommand(string command) throws ioexception {
 runtime runtime = runtime.getruntime();//返回与当前的java应用相关的运行时对象
 //指示java虚拟机创建一个子进程执行指定的可执行程序,并返回与该子进程对应的process对象实例
 process process = runtime.exec(command);
 runtime.gc();//运行垃圾回收器
 string line = null;
 string content = "";
 bufferedreader br = new bufferedreader(new inputstreamreader(process.getinputstream()));
 while((line = br.readline()) != null) {
  content += line + "\r\n";
 }
 system.out.println(content);
 }
}
Copy after login

3.效果预览

  3.1 执行开启命令

How to start and shut down Tomcat server using Java?

  3.2 执行关闭命令

How to start and shut down Tomcat server using Java?

4.常见错误

  执行代码后可能出现:

the catalina_home environment variable is not defined correctly
this environment variable is needed to run this program

  此时需设置环境变量:

How to start and shut down Tomcat server using Java?

  本人设置后运行依然报错,但是将电脑注销一下再次运行即可。

5.说明

  若是执行startup.bat会自动出现弹框,但是若执行tomcat7w.exe(根据tomcat版本有所不同)则不会出现弹框。--仅windows版本,其他版本无.exe文件。

The above is the detailed content of How to start and shut down Tomcat server using Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template