Why is Jetty serving css with text/html content ty

2019-02-26 00:53发布

问题:

I'm using an embedded Jetty server in a Scalatra app. The issue is that it serves css files with text/html content type:

Here is the main method:

package yard.web

import org.eclipse.jetty.server.Server
import org.eclipse.jetty.webapp.WebAppContext
import org.scalatra.servlet.ScalatraListener

object JettyMain {
  def main(args: Array[String]) {
    val server = new Server(9080)
    val context: WebAppContext = new WebAppContext("src/main/webapp", "/")
    context.setServer(server)
    context.setInitParameter(ScalatraListener.LifeCycleKey, "yard.web.ScalatraBootstrap")
    context.addEventListener(new ScalatraListener())
    server.setHandler(context)

    server.start()

    println("Press ENTER to stop server")
    Console.readLine()
    server.stop()
    server.join()
  }
}

The file is located at src/main/webapp/libs/bootstrap/css/bootstrap.css, and served with:

$ curl --head http://localhost:9080/libs/bootstrap/css/bootstrap.css
HTTP/1.1 200 OK
Content-Type: text/html;charset=UTF-8
Last-Modified: Sat, 06 Apr 2013 14:30:35 GMT
Content-Length: 127247
Accept-Ranges: bytes
Server: Jetty(8.1.10.v20130312)

Why is Jetty thinking it's an html file?


Here is the ScalatraBootstrap class for completeness:

package yard.web

import org.scalatra.LifeCycle
import javax.servlet.ServletContext
import yard.Settings
import yard.db.Store

class ScalatraBootstrap extends LifeCycle {
  override def init(context: ServletContext) {

    val settings = Settings.default
    val db = Store(settings).db

    context mount (new MainServlet, "/")
  }
}

Update: Using a ResourceHandler causes the css to be served with correct content type. However, the app doesn't work :(

回答1:

The CSS file is typically served from the org.eclipse.jetty.servlet.DefaultServlet.

Which is declared in the etc/webdefault.xml file in the distribution.

Since you are using embedded mode, you'll want to provide this manually by calling WebAppContext.setDefaultsDescriptor(String) with the path to your etc/webdefault.xml file.

And finally, the mime types themselves are loaded by the DefaultServlet via the mime.properties file, which is loaded by Jetty via a call to Classloader.getResource("/org/eclipse/jetty/http/mime.properties").

Note: the mime.properties file is found in the jetty-http-8.1.10.v20130312.jar file.