I'm using spark with tomcat8.
staticFileLocation("/public")
seemed to work so far.
But there is a problem, all the files are served with content type "text/plain" (or respectively without content-type).
So when including CSS files with absolute path
<link rel="stylesheet" href="/example.css"/>
it will work and be used in FireFox and Chrome. But Chrome throws an error that it must be "text/css". And Internet-Explorer (even the newest Edge-Version) does also so, and is even not loading the CSS!
See SEC7113: "SEC7113 - CSS was ignored due to mime type mismatch"
https://msdn.microsoft.com/en-us/library/hh180764%28v=vs.85%29.aspx
I found a way to solve this, but I'm not sure if this is best practice or intented to be done this way.
I extended the class SparkFilter the following way (unoptimized code):
public class ApplicationFilter extends SparkFilter
{
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
String requestUrl = ((HttpServletRequest) request).getRequestURI().toString();
Map<String, String> mimeMapping = new HashMap<>();
mimeMapping.put(".css","text/css");
mimeMapping.put(".js","text/javascript");
for(Map.Entry<String,String> entry : mimeMapping.entrySet())
{
if(requestUrl.endsWith(entry.getKey()))
{
((HttpServletResponse) response).setHeader("Content-Type",entry.getValue());
}
}
super.doFilter(request, response, chain);
}
}
And changed the class SparkFilter with the ApplicationFilter in the web.xml
<filter-class>com.company.app.ApplicationFilter</filter-class>
Thank you for this. I'd like to add that it helped me solve an issue with the root response returning text/plain instead of text/html as the content type. I used your class and added the following line:
mimeMapping.put("/","text/html");
Thanks for this, I was pulling my hair out trying to figure out why it was working on a local tomcat but not on AWS.
To add a little more confusing stuff, when apache is used as a reverse proxy with tomcat, it adds the content-type...
Most helpful comment
Thanks for this, I was pulling my hair out trying to figure out why it was working on a local tomcat but not on AWS.