I'm writing a filter for Apache Tomcat, I was wondering if there's a way to fetch the mimetypes placed in the /conf/web.xml file configuration file without reading the xml file explicitly. Is there anything available in the Apache Tomcat libraries perhaps?
From the tomcat/conf/web.xml
:
<!-- ======================== Introduction ============================== -->
<!-- This document defines default values for *all* web applications -->
<!-- loaded into this instance of Tomcat. As each application is -->
<!-- deployed, this file is processed, followed by the -->
<!-- "/WEB-INF/web.xml" deployment descriptor from your own -->
<!-- applications. -->
So they are available through the ServletContext.getMimeType method:
@Override
protected void doGet(final HttpServletRequest req,
final HttpServletResponse resp) throws ServletException, IOException {
final ServletContext servletContext = req.getServletContext();
final String mimeType = servletContext.getMimeType("filename.txt");
...
}
I haven't found any other public API for getting the whole MIME type mapping. If you really need it you can get the complete list of the extensions with this ugly hack:
import java.util.Arrays;
import java.lang.reflect.Field;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.RequestFacade;
import org.apache.catalina.core.StandardContext;
...
// ugly reflection hack - do NOT use
final RequestFacade tomcatRequestFacade = (RequestFacade) req;
final Class<? extends RequestFacade> requestFacadeClass =
tomcatRequestFacade.getClass();
try {
final Field field = requestFacadeClass.getDeclaredField("request");
field.setAccessible(true);
final Request tomcatRequest = (Request) field.get(tomcatRequestFacade);
final StandardContext standardContext =
(StandardContext) tomcatRequest.getContext();
final String[] mappings = standardContext.findMimeMappings();
logger.info("mapping list: {}", Arrays.asList(mappings));
} catch (final Exception e) {
logger.error("", e);
}
It works on Tomcat 7.0.21. Since it uses Tomcat's internal classes there is no guarantee that it will work with other Tomcat versions.
Note that you still need to call the ServletContext.getMimeType
to get the MIME types.
The required maven dependency:
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>7.0.21</version>
<scope>provided</scope>
</dependency>