Question
What are the steps to troubleshoot why embedded Tomcat is not serving static content?
<dependency>
<groupId>org.apache.tomcat_embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.43</version>
</dependency>
Answer
When using embedded Tomcat, it may not serve static content due to misconfiguration of resource handling or incorrect file paths. This guide outlines how to resolve these issues effectively.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
@Bean
public WebMvcConfigurer configurer() {
return new WebMvcConfigurer() {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
};
}
}
Causes
- Static resources are not properly mapped in the application's configuration.
- Incorrect directory structure for static content.
- The application does not include the necessary dependencies for static file serving.
Solutions
- Ensure that the resource handler in your application is correctly configured to serve static files.
- Verify that your static content is structured correctly in the project directory, typically under 'src/main/resources/static' for Spring Boot applications.
- Check and add necessary dependencies for serving static content, such as 'tomcat-embed-core' in your build configuration.
Common Mistakes
Mistake: Static files are placed outside the designated static resource folder.
Solution: Ensure all static assets (CSS, JS, images) are located under 'src/main/resources/static'.
Mistake: Missing or incorrect configuration in the Java app for resource mapping.
Solution: Check your application configuration files or annotations for correct resource mappings.
Helpers
- Embedded Tomcat
- Static content not served
- Spring Boot Tomcat
- Tomcat Static Resources
- Troubleshoot Tomcat issue