This is a followup question to my earlier question
The CSS file does not get loaded if I configure like this in the html files.
<link rel="stylesheet" href="./main.css" type="text/css">
or
<link rel="stylesheet" href="main.css" type="text/css">
While Edge and Chrome show no errors at all, Firefox shows this error message:
The stylesheet http://localhost:8080/app/main.css was not loaded because its MIME type, “text/html”, is not “text/css”.
In the Handler this is how the response header is set:
response.setStatus(200);
response.getHeaders().put(HttpHeader.CONTENT_TYPE, MimeTypes.Type.TEXT_HTML_UTF_8.toString());
Content.Sink.write(response, true, msg, callback);
callback.succeeded();
return true;
My question is: How to configure Jetty Server v12 to serve CSS and Javascript files?
Thanks in advance.
You can easily setup a Jetty ResourceHandler
to serve the static files from a url-path and base-resource that you want.
In brief, it will look like this ...
String resourceRoot = // URI string to root of resources
ResourceFactory resourceFactory = ResourceFactory.of(server);
ResourceHandler handler = new ResourceHandler();
handler.setBaseResource(resourceFactory.newResource(resourcesRoot));
handler.setDirAllowed(true);
handlers.addHandler(handler);
The resourceRoot
can be a file-system, a classloader reference, or generally any URL that java supports as well.
The ResourceHandler
can be on it's own, or under a ContextHandler
, or even part of a handler wrapper or selection handler (like a PathMappingsHandler
).
For complete examples of this, see the jetty-examples
project.
ResourceHandler
- https://github.com/jetty/jetty-examples/tree/12.0.x/embedded/file-serverDefaultServlet
- https://github.com/jetty/jetty-examples/tree/12.0.x/embedded/ee10-file-server