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

I am using Servlet 3.0 and want to convert an existing web.xml file to java config. Configuring servlets / filters, etc., It seems pretty soon. 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> 
+7
source share
4 answers

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

 @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); } } 
+6
source

Just write Filter . for example for mime-mapping in web.xml:

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

Instead, we can write a filter:

 @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); } ... } 
+3
source

As far as I know, you cannot install them in your Java configuration. This can only be done in the deployment descriptor of the web application or in the container with the server.

In javadoc ServletContext#getMimeType(String) alludes to this

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

0
source

Using Spring MVC, this method worked for me.

In a web context, add this:

 public class WebContext implements WebMvcConfigurer { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.mediaType("xsd", MediaType.TEXT_XML); } } 
0
source

Source: https://habr.com/ru/post/958018/


All Articles