How to start Tomcat Server in Java - Java @ Desk

Friday, January 13, 2017

How to start Tomcat Server in Java

How to start Tomcat Server in Java

Tomcat server is started using the startup.bat file under bin folder. To start a Tomcat server from command prompt, user is required to hit the command startup.bat and tomcat server gets started in the new command prompt.

To start a server from Java code, its required to create a process of the batch file and execute the process. Below is the source code of the same.

The tomcat server path and the port is mentioned in the properties file along with the Java Path. Properies file is read in the batch file to set the values of Catalina Home and Java Home. If the values are not set in the environment variable for CATALINA_HOME & JAVA_HOME, then they are picked from properties file.

Here is the complete source code.

TomcatStart.java
package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TomcatStartLocalCommand {
 public static void main(String args[]) throws IOException, InterruptedException {
  String command = "C:/Kumar/Documents/ChatBot/myStartUp.bat C:\\Kumar\\Documents\\ChatBot\\tomcat.properties";
  Process process = Runtime.getRuntime().exec(command);
  String ss = null;

  BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));

  System.out.println("Success:");
  while ((ss = stdInput.readLine()) != null) {
   System.out.println(ss);
  }
 }
}




myStartup.bat
@echo off
if not "%CATALINA_HOME%" == "" goto gotHome
set arg1=%1
echo Tomcat Properties Location is %arg1%
For /F "tokens=1* delims==" %%A IN (%arg1%) DO (
 IF "%%A"=="catalinaHome" set catalinaHome=%%B
 )
set CATALINA_HOME=%catalinaHome%
echo Catalina Home is %CATALINA_HOME%
if exist "%CATALINA_HOME%\bin\catalina.bat" goto gotHome

:gotHome
if not "%JAVA_HOME%" == "" goto gotJava
set arg1=%1
echo Tomcat Properties Location is %arg1%
For /F "tokens=1* delims==" %%A IN (%arg1%) DO (
 IF "%%A"=="javaHome" set javaHome=%%B
 )
set JAVA_HOME=%javaHome%
echo Java Home is %JAVA_HOME%
if exist "%JAVA_HOME%\bin\java.exe" goto gotJava


:gotJava
set "EXECUTABLE=%CATALINA_HOME%\bin\startup.bat"
call "%EXECUTABLE%"


tomcat.properties
catalinaHome=C:\Kumar\Softwares\apache-tomcat-8.0.38
javaHome=C:\Program Files\Java\jre1.8.0_111
port=8080






No comments:

Post a Comment