转载

Spring中的ResourceHandler

在一个Web项目中往往需要处理一些静态资源的请求,比如css,js,image文件的等。Spring Boot提供了一种很简单的方式,即使用默认配置。

在application.properties的 配置清单 中可以看到这些属性:

配置项 默认值 含义
spring.resources.add-mappings true Whether to enable default resource handling.
spring.resources.static-locations classpath:/META-INF/resources/ , classpath:/resources/ , classpath:/static/ , classpath:/public/ Locations of static resources. Defaults to classpath:[/META-INF/resources/, /resources/, /static/, /public/].

也就是说,默认是启用了静态资源映射的,并且,当文件在 classpath:/META-INF/resources/ , classpath:/resources/ , classpath:/static/ , classpath:/public/ 这四个目录下的话可以直接返回。

但是,如果开发者不希望将这四个目录定为静态资源目录,而是只指向某一个(既可以是上面四个目录其中之一,也可以是一个自定义的目录),那么可以修改配置文件中的上述配置项,或者通过Java代码的方式进行配置。

使用Java代码配置

首先在Spring的ComponentScan可以扫描到的目录创建一个WebConfig类,然后重写addResourceHandlers方法:

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/","file:///E:/");
    }
}
复制代码

其中,addResourceLocations可以支持添加多个目录,并且这些目录类型涵盖了classpath/file/http:

/**
 * Add one or more resource locations from which to serve static content.
 * Each location must point to a valid directory. Multiple locations may
 * be specified as a comma-separated list, and the locations will be checked
 * for a given resource in the order specified.
 * <p>For example, {{@code "/"}, {@code "classpath:/META-INF/public-web-resources/"}}
 * allows resources to be served both from the web application root and
 * from any JAR on the classpath that contains a
 * {@code /META-INF/public-web-resources/} directory, with resources in the
 * web application root taking precedence.
 * <p>For {@link org.springframework.core.io.UrlResource URL-based resources}
 * (e.g. files, HTTP URLs, etc) this method supports a special prefix to
 * indicate the charset associated with the URL so that relative paths
 * appended to it can be encoded correctly, e.g.
 * {@code [charset=Windows-31J]https://example.org/path}.
 * @return the same {@link ResourceHandlerRegistration} instance, for
 * chained method invocation
 */
public ResourceHandlerRegistration addResourceLocations(String... resourceLocations);
复制代码

上面的配置代码会覆盖原来的默认设置,导致默认指定的四个目录失效。

原文  https://juejin.im/post/5dc7f7675188253afe726ea0
正文到此结束
Loading...