Spring MVC (Boot) does not send MIME type for certain files (WOFF, etc)

Patrick Cornelissen picture Patrick Cornelissen · Dec 23, 2014 · Viewed 9.2k times · Source

I am writing a spring boot based application and noticed a few warnings in chrome. It complains that for example web fonts (extension woff) are send as plain/text instead of their correct mime type.

I am using the regular mechanism for static files without special configuration. The sourcecode I found looks like it's not possible to add more mimetypes for the "stock" ResourceHandler. The Resourcehandler dispatches the mime type recognition to the servlet container, which is the default tomcat for spring-boot 1.2.

Am I missing something? Does someone know an easy way to to enhance the resource mapping to serve more file types with the correct mime type?

Right now I'm thinking to write a filter that is triggered for static content and patches missing mimetypes after the fact. Maybe I should create a feature request at springsource... ;-)

Answer

Patrick Cornelissen picture Patrick Cornelissen · Dec 23, 2014

OK, found it myself :-)

In Spring boot you can customize the servlet container with this customizer and add new mimetypes there.

(UPDATE)

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);
    }
}