2
votes

With jetty, you can easily produce "html" response importing external file like :

<head>
<link rel="stylesheet" type="text/css" href="myStyle.css">
<script src="myScript.js"></script>
<head>

However, where do you put myStyle.css and myScript.js, when jetty is embedded?

Especially when the jetty server is in a large OpenSource project not written by you?

Is there by any chance a nice out.println(???); in the servlet.doGet that would provide the answer, or something similar?

1

1 Answers

2
votes

I think this depends on how you package your jar. For example if you package it like a one-jar all classes and resources from your own code and dependencies are exploded into a jar/war. Then you'll have to set the webcontext to Jetty accordingly. A couple of examples using Maven and Gradle that might shine some light:

http://open.bekk.no/embedded-jetty-7-webapp-executable-with-maven
https://github.com/jhannes/java-ee-turnkey/

Given the latter example it is resolved something along these lines:

URL[] urls = ((URLClassLoader) AbstractServerMain.class.getClassLoader()).getURLs();
WebAppContext context;
if (urls.length == 1 && urls[0].getFile().endsWith(".war")) {
    context = new WebAppContext(urls[0].getFile(), contextRoot);
} else {
    context = new WebAppContext("src/main/webapp", contextRoot);
}

This will ensure that you can also run from Eclipse/IntelliJ etc.
The first example uses ProtectionDomain

// Get the war-file
ProtectionDomain protectionDomain = Main.class.getProtectionDomain();
String warFile = protectionDomain.getCodeSource().getLocation().toExternalForm();
String currentDir = new File(protectionDomain.getCodeSource().getLocation().getPath()).getParent();

// Add the warFile (this jar)
WebAppContext context = new WebAppContext(warFile, contextPath);

This is not so friendly when running from your Eclipse/IntelliJ though.

Should you choose to not do a one-jar and go for the Gradle application-plugin or Maven appassembler you might have to either copy the resources into your "Main-jar" (the one firing up Jetty) or setting the webcontext to the jar containing the resources. Revealing now that I'm not too familiar on how to...