21

I successfully embedded Jetty on a test application. It can serve files without issues. Now I want to know if it's possible for Jetty to serve files that are inside its own Jar file.

Does anyone know if that's possible?

juan
  • 74,179
  • 49
  • 153
  • 188
LaSombra
  • 789
  • 1
  • 7
  • 12

4 Answers4

38

An example is listed on the Jetty embedding page at http://docs.codehaus.org/display/JETTY/Embedding+Jetty

The trick is to create a File URL to your classpath location.

String webDir = this.class.getClassLoader().getResource("com/company/project/mywebdir").toExternalForm();

ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.setResourceBase(webDir);
Uriah Carpenter
  • 6,346
  • 30
  • 28
  • @phtrivier The class where you instantiate org.mortbay.jetty.Server or org.eclipse.jetty.server.Server. – Uriah Carpenter Dec 02 '11 at 17:24
  • any idea what to do if `request.getRequestDispatcher(...).forward(req, resp)` is not finding `.jsp` files under `WEB-INF` when running from a JAR file? – Erik Kaplun Apr 09 '14 at 02:58
  • The link above is out of date, and it seems with Jetty version 9.4.11.v20180605 the class ServletContextHandler does not exist. – JRSofty Sep 01 '18 at 18:18
5

It's pretty simple, if you throw Spring into the equation. And here it goes:

 ...

 WebAppContext webAppContext = new WebAppContext();
 webAppContext.setServer(server);
 webAppContext.setContextPath("/");
 webAppContext.setResourceBase(new ClassPathResource("webapp").getURI().toString());

 server.addHandler(webAppContext); 

 ....

That will make jetty find the necessary web resources inside the jar file.

James Selvakumar
  • 2,317
  • 1
  • 18
  • 27
-4

Maybe more of a hack, but aren't JAR files actually ZIPs? (not sure) Could you unzip them into a temporary folder and serve them from there?

lod3n
  • 2,843
  • 12
  • 16
  • 1
    I could, but I want a self-contained web application inside a Jar for simplicity purposes. :) – LaSombra Sep 22 '09 at 23:05
  • 1
    Actually jetty does this internally if you try to set a webapp folder, so he wasn't that far off. – fd8s0 Aug 12 '13 at 10:56
-8

Found the answer and it's not Jetty, it's Winstone. http://winstone.sf.net

LaSombra
  • 789
  • 1
  • 7
  • 12
  • 2
    Down-voting because even though you're the OP, this solution really isn't a solution. And it would be an extremely rare situation where a guy stumbling upon the issue you faced would go with this solution. – alok Jul 23 '16 at 06:14