Spring Boot
static content
troubleshooting
web development
Java

Spring Boot not serving static content

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Spring Boot is widely recognized for its ability to simplify the development of Java applications, particularly when it comes to creating stand-alone, production-grade Spring-based applications. One of its many features is its built-in ability to serve static content. Despite this, developers occasionally encounter scenarios where Spring Boot fails to serve static content as expected. This article explores the technical reasons behind such issues, examines common pitfalls, and provides solutions for addressing these problems.

Understanding Static Content in Spring Boot

By default, Spring Boot serves static content from the following locations in the classpath:

  • /static
  • /public
  • /resources
  • /META-INF/resources

When a request is made for static content, Spring Boot searches these directories in the order listed and serves the first matching resource it finds.

Common Reasons for Static Content Not Being Served

1. Incorrect Directory Placement

One of the most common reasons Spring Boot does not serve static content is the placement of resources in incorrect directories. Static resources must be placed in one of the recognized locations mentioned above.

Solution: Verify that your resources (e.g., HTML, CSS, JavaScript files) are correctly placed in any of the default directories.

2. Configuration Issues

Spring Boot's auto-configuration can sometimes be overridden unintentionally in application.properties or application.yml.

Solution: Ensure that you haven't explicitly disabled static resources by configuring the spring.resources.static-locations property incorrectly. Here’s an example configuration in application.properties that sets a custom static resource location:

properties
spring.web.resources.static-locations=classpath:/custom-static/

Ensure that the specified folder exists and contains the resources you intend to serve.

3. DispatcherServlet Mapping

Spring Boot's DispatcherServlet handles all requests, and if not configured properly, it may affect static resource serving.

Solution: Ensure that DispatcherServlet mappings do not overlap with static resource paths. If necessary, reconfigure the mappings in such a way that they don't interfere with the default static resource handling.

java
1@Bean
2public ServletRegistrationBean<DispatcherServlet> dispatcherRegistration(DispatcherServlet dispatcherServlet) {
3    ServletRegistrationBean<DispatcherServlet> registration = new ServletRegistrationBean<>(dispatcherServlet);
4    registration.addUrlMappings("/");
5    return registration;
6}

4. Custom WebMvcConfigurerAdapter

Implementing WebMvcConfigurer (previously WebMvcConfigurerAdapter) can override default static content configurations.

Solution: When defining a custom WebMvcConfigurer, ensure static resource handlers are properly configured:

java
1@Configuration
2public class WebConfig implements WebMvcConfigurer {
3    
4    @Override
5    public void addResourceHandlers(ResourceHandlerRegistry registry) {
6        registry.addResourceHandler("/resources/**")
7                .addResourceLocations("classpath:/resources/");
8    }
9}

5. Absence of ResourceChain

By default, Spring Boot uses a ResourceChain for better resource handling. Disabling the resource chain might lead to fewer features being available.

Solution: Enable the resource chain if possible:

java
spring.web.resources.chain.enabled=true

Handling Security Configurations

Security configurations can sometimes inadvertently block access to static resources. Specifically, Spring Security, if not configured correctly, might prevent static content from being served.

Solution: Override WebSecurityConfigurerAdapter to permit public access to static resources:

java
1@Override
2public void configure(WebSecurity web) throws Exception {
3    web.ignoring().antMatchers("/resources/**", "/static/**", "/public/**", "/webjars/**");
4}

Troubleshooting Checklist

Below is a table summarizing the key points when troubleshooting why Spring Boot might not serve static content:

Issue TypeDescriptionSolution
Incorrect DirectoryResources not in correct locationsPlace resources in /static, /public, etc.
Configuration OverrideProperties overriding default behaviorCheck application.properties for misconfigs
DispatcherServletMisdirected requests due to servlet mappingEnsure servlet mappings don't interfere
Custom WebMvcConfigurerOverriding default static handling mechanismsProperly configure resource handlers
Security ConfigurationSpring Security blocking static resourcesConfigure security to allow access

Additional Subtopics

Considerations for WebJars

WebJars provide an elegant solution for managing web libraries using JAR packaging. Spring Boot natively supports WebJars, allowing you to utilize resources from /webjars/**.

To ensure WebJars function correctly, verify they are included as dependencies in your pom.xml or build.gradle and correctly requested in your HTML files.

Custom Static Locations

In situations where you require custom static locations, extend the default static location strategy to include these new paths. This often involves a combination of property configuration and custom MVC configuration.

Monitoring and Logging

Utilize logging to monitor static resource requests and determine if they are being intercepted or mishandled. Configuring higher-level logging for debugging purposes can give insights into potential misconfigurations.

properties
logging.level.org.springframework.web=DEBUG

Spring Boot provides ample support for serving static content, but understanding its default behavior and configuration nuances is crucial for effective application development. By closely inspecting configurations, directory setups, and security settings, you can overcome obstacles related to serving static content in Spring Boot applications.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.