This PowerShell script automates the process of building, deploying, and managing JSP web applications on Apache Tomcat, opening the browser, and reloading the page with no user interaction.
This video demonstrates the dev
deployment mode, which directly deploys files from the development folder. This method is significantly faster as it skips the Maven build process.
This video demonstrates the mvn
deployment mode, which builds the project using Maven and deploys the generated WAR file. This method is slower due to the Maven build process.
Automatically builds projects using Maven
This feature ensures that the project is built using Maven, compiling the source code and generating a deployable WAR file.
$process = Start-Process -FilePath "mvn" -ArgumentList "clean package" -PassThru -Wait -NoNewWindow
if ($process.ExitCode -ne 0) {
Write-Host "[ERROR] Maven build failed. Exiting." -ForegroundColor Red | Out-Null
exit 1
}
Explanation: The script starts the Maven process using mvn clean package
. If the Maven build fails (i.e., the exit code is non-zero), an error message is displayed, and the script terminates.
Deploys WAR files to the Tomcat `webapps` directory
Once the Maven build completes successfully, the generated WAR file is deployed to the Tomcat webapps
directory.
$WAR_FILE = Get-ChildItem -Path "$PROJECT_DIR\target" -Filter "*.war" | Select-Object -First 1 -ExpandProperty FullName
$APP_NAME = [System.IO.Path]::GetFileNameWithoutExtension($WAR_FILE)
if (-not $WAR_FILE) {
Write-Host "[ERROR] No WAR file found. Closing Tomcat..." -ForegroundColor Red
exit 1
}
Copy-Item -Path $WAR_FILE -Destination "$TOMCAT_HOME\webapps\"
INFO "New WAR file deployed"
Explanation: The script searches for the WAR file in the project's target directory and deploys it to the Tomcat webapps
directory. If no WAR file is found, it terminates with an error message.
Supports two deployment modes: `dev` and `mvn`
The script now supports two deployment modes:
dev
: Directly deploys files from the development folder.mvn
: Builds the project using Maven and deploys the generated WAR file.
function deploy {
param (
[ValidateSet("dev", "mvn")]
[string]$Type
)
cleanOldDeployments
if ($Type -eq "dev") {
# Deploy from development folder
} elseif ($Type -eq "mvn") {
# Build and deploy using Maven
}
}
Explanation: The deploy
function now accepts a Type
parameter to specify the deployment mode. This allows for more flexibility in how the application is deployed.
Starts or stops Tomcat based on its running status
The script includes functionality to start or stop Tomcat depending on the given action (start
or stop
).
function tomcat {
param (
[ValidateSet("start", "stop", "reload")]
[string]$Action
)
$javaExecutable = "$env:JAVA_HOME\bin\java.exe"
Start-Process -FilePath $javaExecutable `
-ArgumentList "-cp", $classpath, $catalinaOpts, $mainClass, $Action `
-NoNewWindow `
-RedirectStandardOutput $logOut `
-RedirectStandardError $logErr `
-Wait
}
Explanation: The tomcat
function takes an action parameter (start
, stop
, or reload
) and starts, stops, or reloads the Tomcat server accordingly by executing the Java process with the appropriate arguments.
Reloads the application if Tomcat is already running
If Tomcat is already running, the script will reload the application rather than restarting the server.
if ($tomcatRunning) {
try {
$creds = New-Object System.Management.Automation.PSCredential("admin", (ConvertTo-SecureString "admin" -AsPlainText -Force))
Invoke-WebRequest -Uri "http://localhost:8080/manager/text/reload?path=/$APP_NAME" -Method Get -Credential $creds | Out-Null
INFO "Tomcat reloaded"
} catch {
Write-Host "[ERROR] Failed to reload Tomcat. Check your credentials and Tomcat manager settings." -ForegroundColor Red
exit 1
}
} else {
Tomcat -Action start
}
Explanation: If Tomcat is running, the script uses the Tomcat manager's API to reload the application without restarting the server. If Tomcat is not running, it starts the server first. Note: The script will crash if the following line is not added to apache-tomcat\conf\tomcat-users.xml
:
<user username="admin" password="admin" roles="manager-gui,manager-script"/>
This line grants the necessary permissions to the Tomcat manager for reloading the application.
In newer versions of PowerShell, you might need to include the -AllowUnencryptedAuthentication
flag when running the script to enable basic authentication for the Tomcat manager API. The rest of the command should remain unchanged.
Example:
Invoke-WebRequest -Uri "http://localhost:8080/manager/text/reload?path=/$APP_NAME" -Method Get -Credential $creds -AllowUnencryptedAuthentication
Without this flag, you might encounter errors related to unencrypted communication during authentication.
Opens or refreshes the application in Google Chrome
The script ensures the application is opened or refreshed in Google Chrome after deployment.
$chromeProcesses = Get-Process -Name "chrome" -ErrorAction SilentlyContinue
if ($chromeProcesses) {
$chromeOpened = $false
foreach ($process in $chromeProcesses) {
$chromeTitle = $process.MainWindowTitle
if ($chromeTitle -like "*$APP_NAME*") {
$chromeOpened = $true
[System.Windows.Forms.SendKeys]::SendWait("^{F5}") # Ctrl+F5 for hard refresh
INFO "Google Chrome reloaded"
break
}
}
if (-not $chromeOpened) {
INFO "Opening Google Chrome"
Start-Process "chrome" "http://localhost:8080/$APP_NAME"
}
} else {
INFO "Opening Google Chrome"
Start-Process "chrome" "http://localhost:8080/$APP_NAME"
}
Explanation: The script checks if Google Chrome is already open and refreshes the tab with the deployed application. If Chrome is not open, it launches a new instance with the application URL.
Action | Description | Subactions (if applicable) |
---|---|---|
start | Starts the Tomcat server | None |
stop | Stops the Tomcat server | None |
deploy | Deploys the application to Tomcat | dev : Deploy from development folder mvn : Build and deploy using Maven |
clean | Cleans previous deployments | None |
help | Displays help message | None |
Before using this script, ensure the following requirements are met:
- Java Development Kit (JDK): Installed and
JAVA_HOME
environment variable is correctly set. - Apache Tomcat: Installed and
CATALINA_HOME
environment variable is correctly set. - Maven: Installed and added to the system's
PATH
. - Google Chrome: Installed for automatic browser interaction.
This script assumes that the working directory contains the pom.xml
file (for Maven builds) or a valid project structure (for dev
deployment). If these are missing, the script will not run.
This script is designed to be extendable. You can add new functionality such as pre-deployment checks, custom notifications, or integrate with other tools.
- Custom Deployment Notifications: You can modify the script to send email or Slack notifications after deployment.
- Custom Build Scripts: Add new Maven goals or other build scripts as part of the
mvn clean package
command.
For Visual Studio Code users, the script can be configured to run automatically on file save using the Run on Save extension.
- Install the extension from this repository: vscode-run-on-save.
- Add the following configuration to your VS Code settings:
"runOnSave.shell": "PowerShell",
"runOnSave.commands": [
{
"match": ".jsp",
"command": "tom deploy dev",
}
],
"runOnSave.defaultRunIn": "terminal"
- If JAVA_HOME or CATALINA_HOME is not set correctly, the script will terminate with an appropriate error message.
- Maven build failures will stop further deployment.
- Missing WAR files or invalid project structures will prompt Tomcat shutdown before exit.
This script is licensed under the MIT License.