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

1

13

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

Corner answered 23/12, 2014 at 9:14 Comment(0)
C
33

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);
    }
}
Corner answered 23/12, 2014 at 12:58 Comment(8)
I've done the same thing with my application, setting the js and css types, but for some reason still getting incorrect mime types. Any suggestions of how to ensure it works?Bird
js and css should work out of the box! Are you sure that you haven't misconfigured spring MVC?Corner
You're right. I have got it configured badly. It's actually getting a login page rather than the JS and CSS files, hence the mime type error.Bird
Thanks Anton for the enhancement regarding woff2Corner
Please note that this only works with an Embedded (runnable jar) servlet container.Pinebrook
The embedded-tomcat8 tag is present. (And most spring-boot apps are using an embedded container)Corner
@Patrick Cornelissen, any ideas how to do that for external tomcat ?Niklaus
When you use a regular tomcat you should be able to put that in the web.xmlCorner

© 2022 - 2024 — McMap. All rights reserved.