Spring MVC(Boot)不会为某些文件发送MIME类型(WOFF等)

时间:2014-12-23 09:14:23

标签: spring-mvc mime-types spring-boot embedded-tomcat-8

我正在编写一个基于spring boot的应用程序,并注意到chrome中的一些警告。它抱怨说例如web字体(扩展名woff)是以普通/文本而不是正确的mime类型发送的。

我在没有特殊配置的情况下使用静态文件的常规机制。 我发现的源代码看起来不可能为" stock"添加更多的mimetypes。 ResourceHandler。 Resourcehandler将mime类型识别调度到servlet容器,这是spring-boot 1.2的默认tomcat。

我错过了什么吗?有人知道一种简单的方法来增强资源映射以使用正确的mime类型提供更多文件类型吗?

现在我正在考虑编写一个针对静态内容触发的过滤器,并在事后删除mimetypes。也许我应该在springsource创建一个功能请求......; - )

1 个答案:

答案 0 :(得分:27)

好的,自己找到了: - )

在Spring启动中,您可以使用此自定义程序自定义servlet容器,并在那里添加新的mimetypes。

更新

Spring-boot 2.x:

@Component
public class ServletCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
        mappings.add("woff", "application/x-font-woff");
        factory.setMimeMappings(mappings);
    }
}

Spring-boot 1.x:

@Component
public class ServletCustomizer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
        mappings.add("woff","application/font-woff");
        mappings.add("woff2","application/font-woff2");
        container.setMimeMappings(mappings);
    }
}