Issue
I'm getting 404 consistently for a Gradle spring project while running on tomcat 8.5. I created a simple project from https://start.spring.io and imported it into the spring tool suite.
When I run it as spring boot app, I'm able to hit the endpoint http://localhost:8080/healthCheck
but when I add it to server I created (tomcat 8.5), I'm getting a 404 error on the same endpoint.
This is my simple controller:
@RestController
public class HealthCheckController {
@GetMapping("/healthCheck")
public String healthCheck() {
return "API is accessible";
}
}
This is my build.gradle:
plugins {
id 'org.springframework.boot' version '2.5.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.demo'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-tomcat:2.5.4'
}
test {
useJUnitPlatform()
}
And this is my main class:
@SpringBootApplication
public class PracticeApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(PracticeApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(PracticeApplication.class);
}
}
I have changed the server location to use Tomcat Installation and hence am able to hit http://localhost:8080
and it comes up with tomcat homepage.
Here's my directory structure for reference:
I'm new to gradle and spring so apologies if its a stupid thing that I'm doing wrong.
Solution
So turns out Apache Tomcat does not take jar files and to run spring boot app on an external tomcat server (non-embedded ones), WAR file is needed to be created.
I added war to my build.gradle and gave it an alias as well
plugins {
id 'org.springframework.boot' version '2.5.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'war'
}
war {
archiveName = 'practice.war'
}
After adding the above, I refreshed the Gradle project and restarted the server and then I hit the below endpoint:
http://localhost:8080/practice/healthCheck
This is different from how we hit the above endpoint on the embedded server which is:
http://localhost:8080/healthCheck
Another way to run this is to go to build/libs/
and copy the war into ROOT directory, then run startup.bat
from apache/bin/
Answered By - Billy
Answer Checked By - David Goodson (JavaFixing Volunteer)