Embedded Jetty looking for files inside its Jar file

20,036

Solution 1

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

Solution 2

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.

Share:
20,036
LaSombra
Author by

LaSombra

Learning how to be a developer

Updated on July 09, 2022

Comments

  • LaSombra
    LaSombra almost 2 years

    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?

  • LaSombra
    LaSombra over 14 years
    I could, but I want a self-contained web application inside a Jar for simplicity purposes. :)
  • LaSombra
    LaSombra almost 14 years
    Thanks. I did it with Maven + Assembly plugin :)
  • Uriah Carpenter
    Uriah Carpenter over 12 years
    @phtrivier The class where you instantiate org.mortbay.jetty.Server or org.eclipse.jetty.server.Server.
  • fd8s0
    fd8s0 over 10 years
    Actually jetty does this internally if you try to set a webapp folder, so he wasn't that far off.
  • Wim Deblauwe
    Wim Deblauwe over 10 years
    What type is 'server' ?
  • Erik Kaplun
    Erik Kaplun about 10 years
    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?
  • fionbio
    fionbio over 8 years
    @WimDeblauwe org.eclipse.jetty.server.Server
  • alok
    alok almost 8 years
    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.
  • JRSofty
    JRSofty over 5 years
    The link above is out of date, and it seems with Jetty version 9.4.11.v20180605 the class ServletContextHandler does not exist.