温馨提示×

SpringBoot中怎么处理静态资源

小亿
87
2024-03-07 12:54:24
栏目: 编程语言

Spring Boot中提供了一个默认的静态资源处理器,可以很方便地处理静态资源文件。在Spring Boot的配置文件中,可以通过设置spring.resources.static-locations属性来指定静态资源文件的位置。默认情况下,Spring Boot会在classpath:/META-INF/resources/classpath:/resources/classpath:/static/classpath:/public/目录中查找静态资源文件。

可以将静态资源文件放置在src/main/resources/static目录下,Spring Boot会自动将这些文件暴露出来,可以在浏览器中直接访问。例如,将一个名为example.jpg的图片文件放置在src/main/resources/static/images/目录下,访问http://localhost:8080/images/example.jpg即可查看图片。

除了使用默认静态资源处理器外,还可以通过实现WebMvcConfigurer接口来自定义静态资源处理器。可以通过重写addResourceHandlers方法来配置自定义的静态资源文件路径和URL映射。例如:

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

上述代码片段配置了一个名为custom的URL映射,将classpath:/custom/目录下的静态资源文件暴露出来。可以通过访问http://localhost:8080/custom/example.jpg来查看example.jpg文件。

0