【问题标题】:Why is Jetty serving css with text/html content type为什么 Jetty 使用 text/html 内容类型提供 css
【发布时间】:2013-03-28 23:04:27
【问题描述】:

我在 Scalatra 应用程序中使用嵌入式 Jetty 服务器。问题是它为 css 文件提供 text/html 内容类型:

这里是主要方法:

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()
  }
}

该文件位于src/main/webapp/libs/bootstrap/css/bootstrap.css,并提供给:

$ 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)

为什么 Jetty 认为它是一个 html 文件?


为了完整起见,这里是 ScalatraBootstrap 类:

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, "/")
  }
}

更新:使用 ResourceHandler 会导致 css 以正确的内容类型提供。但是,该应用程序不起作用:(

【问题讨论】:

  • 你使用的是什么版本的 scala 和 scalatra?
  • scala 2.10,scalatra 2.2
  • 我用你的代码、相同的版本和一个虚拟控制器制作了一个简单的应用程序。我仍然可以看到返回的正确内容类型,以及将请求路由到主控制器。问题可能出在其他地方。

标签: scala jetty embedded-jetty


【解决方案1】:

CSS 文件通常由 org.eclipse.jetty.servlet.DefaultServlet 提供。

在分发版的etc/webdefault.xml 文件中声明。

由于您使用的是嵌入式模式,因此您需要通过调用 WebAppContext.setDefaultsDescriptor(String) 手动提供此文件,并附上您的 etc/webdefault.xml 文件的路径。

最后,mime 类型本身由DefaultServlet 通过mime.properties 文件加载,该文件由Jetty 通过调用Classloader.getResource("/org/eclipse/jetty/http/mime.properties") 加载。

注意:mime.properties 文件位于 jetty-http-8.1.10.v20130312.jar 文件中。

【讨论】:

  • mime.properties 在那里并且有正确的 css 行。顺便说一句,我正在使用 sbt 来管理部门。使用ResourceHandler 修复了内容类型,但我找不到将它与WebAppContext 结合的方法。另外,我实际上并没有使用任何web.xml 文件。
  • 有没有web.xml 并不重要。 webdefault.xml 仍然是必需的。获取它的副本,修改它以满足您的需要(例如删除 jsp 支持),获取对它的文件引用,并通过 WebAppContext.setDefaultsDescriptor(String) 设置该文件引用。这是假设 DefaultServlet 正在为您的 CSS 文件提供服务。可能是 Scala 本身为 CSS 服务,如果是这样,您需要配置 Scala。
  • 你是对的。问题是 Scala 正在为 css 服务。当我添加具有正确设置的web.xml 以让default-servlet 为他们服务时,一切正常。
猜你喜欢
  • 2020-02-24
  • 2021-12-29
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 2014-03-08
  • 1970-01-01
相关资源
最近更新 更多