How to specify mime-mapping using servlet 3.0 java config?
Asked Answered
N

4

8

I am using Servlet 3.0 and looking to convert my existing web.xml file to java config. Configuring servlets/filters etc seems to be pretty straight away. I can't figure out how to convert the following mime-mapping. Can anyone help me out?

<mime-mapping>
    <extension>xsd</extension>
    <mime-type>text/xml</mime-type>
</mime-mapping>
Necroscopy answered 13/11, 2013 at 17:53 Comment(0)
M
7

I faced this problem in a Spring Boot application. My solution was to create a class that implements org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer as following:

@Configuration
public class MyMimeMapper implements EmbeddedServletContainerCustomizer {
  @Override
  public void customize(ConfigurableEmbeddedServletContainer container) {
    MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
    mappings.add("xsd", "text/xml; charset=utf-8");
    container.setMimeMappings(mappings);
  }
}
Mera answered 27/5, 2014 at 11:59 Comment(3)
Interesting, I didn't know that this class existed (org.springframework.boot.context.embedded.MimeMappings). While I was hoping for a solution that doesn't depend on Spring Boot, this certainly works for now. Thanks for sharing.Necroscopy
I haven't looked any deeper into this, no.Mera
@Samuli Kärkkäinen above code is for embeded tomcat, what about external tomcat ?Centeno
P
3

Just write a Filter. e.g. for mime-mapping in web.xml:

<mime-mapping>
    <extension>mht</extension>
    <mime-type>message/rfc822</mime-type>
</mime-mapping>

We can write a Filter instead:

@WebFilter("*.mht")
public class Rfc822Filter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        resp.setContentType("message/rfc822");
        chain.doFilter(req, resp);
    }

    ...
}
Phrenic answered 24/12, 2015 at 8:7 Comment(0)
Q
1

Using spring MVC, this method worked for me.

In the web-context, add this:

public class WebContext implements WebMvcConfigurer {

  @Override
  public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.mediaType("xsd", MediaType.TEXT_XML);
  }
}
Quartern answered 19/6, 2019 at 13:2 Comment(0)
S
0

As far as I know, you cannot set them in Java configuration. You can only do this in the web application's deployment descriptor or your serlvet container's.

The javadoc of ServletContext#getMimeType(String) hints at this

The MIME type is determined by the configuration of the servlet container, and may be specified in a web application deployment descriptor.

Shaper answered 13/11, 2013 at 18:9 Comment(1)
This is exactly where I wound up. I am still hoping that there is another way.Necroscopy

© 2022 - 2024 — McMap. All rights reserved.