简体   繁体   中英

Serving static files with content negotiation using embedded Jetty

I have an application using embedded Jetty to serve both the frontend of the site but also the API.

It's written in Scala, but that's not really relevant. My file that sets everything up looks like this:

val servlet = new ServletHolder(Servlet)

val frontend = new ServletHolder(new DefaultServlet())
frontend.setInitParameter("resourceBase", "frontend")

val handler = new ServletContextHandler()
handler.addServlet(servlet, "/api/*")
handler.addServlet(frontend, "/*")

val server = new Server(8080)
server.setHandler(handler)
server.start()

However, static content served from / requires that I use file extensions for my static content - I would like to use content negotiation so that these are not required. Is this possible?

You are not serving static files if you want to use content negotiation.

Content Negotiation is a fundamental concept of HTTP, and it really for the content that is being served from the (hand waving) "resource", that you are requesting.

Serving static files is a specialized form of "resource", where the mime-type / content-type is known based on its file extension.

The DefaultServlet (which is doing the static file serving in your example) has 1 more feature on top of the this specialization, but not for content-type, but rather content-encoding (you can pre-compress your static resources by creating a <filename>.gz file that sits next to the original file, if the requesting client indicates that they can accept gzip, then this <filename>.gz is served instead of the uncompressed <filename> version.

In order to accomplish this goal, you'll need to write something that serves the static files in a way that makes sense for you.

What you'll need if you want to do this yourself.

  • A new servlet on url-pattern /*
  • The new servlet's .init() creates an in-memory data structure that houses all of the known static files you have, plus their extensions, and mime-types.
  • The new servlet's .doGet() will handle any incoming requests by seeing if there is an acceptable resource to serve based on this in-memory lookup. Serve the actual content you want from this in-memory lookup.
  • Don't forget to support ETag, Ranged requests, Server response Cache, HTTP Cache, and Gzip.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM