How to handle static resources in SpringBoot

Spring Boot comes with a default static resources handler that makes it easy to handle static resource files. In the Spring Boot configuration file, you can specify the location of static resource files by setting the spring.resources.static-locations property. By default, Spring Boot will search for static resource files in the directories classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, and classpath:/public/.

Static resource files can be placed in the src/main/resources/static directory. Spring Boot will automatically expose these files, allowing them to be accessed directly in a browser. For example, placing an image file named example.jpg in the src/main/resources/static/images/ directory will allow you to view the image by accessing http://localhost:8080/images/example.jpg.

In addition to using the default static resource handler, you can also customize the static resource handler by implementing the WebMvcConfigurer interface. You can configure custom static resource file paths and URL mappings by overriding the addResourceHandlers method. For example:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/custom/**").addResourceLocations("classpath:/custom/");
    }
}

The code snippet above sets up a URL mapping named “custom”, exposing static resource files located under classpath:/custom/ directory. You can view the “example.jpg” file by accessing http://localhost:8080/custom/example.jpg.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds