Tom
Tom

Reputation: 19302

Jetty 6: static content with directory listing

I'm using Jetty 6 as an embedded web server in my Java app. Heretofore, I've had no reason to serve static content, but now I'd like to not only serve static content but also show directory listings.

I've tried using the ResourceHandler class to do this, but at some point mortbay removed the ability for ResourceHandler to do directory listing.

I'd like to do this without adding .jsp or servlet functionality and without web.xml configuration. In short I'm trying to do this programmatically.

For the life of me, I can't find any examples for this online. Could someone point me in the right direction?

Thanks much!

Upvotes: 1

Views: 3562

Answers (2)

Tom
Tom

Reputation: 19302

Okay, I figured out how to get Jetty to do what I wanted, which once again was to host some static content in addition to handling some custom servlets.

Ostensibly, the way to do this was to create a DefaultServlet and set the resourceBase and pathSpec accordingly, to allow me to host some directory on /www/*. However, this never worked. In fact, I couldn't find any explanation as to how the pathSpecs actually work or are supposed to be defined.

Thus, I had to create an additional ServletHandler and Context and add both my orginal Context and the new one for static content hosting to the Server.

I did that like so:


Server srv = new Server( port );

//  create context and handler for my servlets
Context ctx = new Context();
ServletHandler sh = new ServletHandler();

//  ... adding servlets here ...

//  create context and handler for static content
ServletHandler sh2 = new ServletHandler();
ServletHolder holder = new ServletHolder( new DefaultServlet() );
holder.setInitParameter("resourceBase", staticResourceBase);
sh2.addServletWithMapping( holder, "/*" );
staticContext.setContextPath(staticPathSpec);
staticContext.setServletHandler(sh2);

//  add both contexts to server
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] { staticContext, ctx });
srv.setHandler(contexts);



This may not be the preferred way to do this, but it did allow me to add static content hosting to my Jetty-based app programmatically.

Upvotes: 3

David Parks
David Parks

Reputation: 32081

If you have a webapp and just jetty running, I think the default is to serve any static content out of the webapp root directory (e.g. the same directory that WEB-INF resides in). So for example you might have the following directories:

mywebapp
 - WEB-INF
 - static
     - site_img.gif

And you can now serve http://mysite.com/static/site_img.gif

Correct me if I'm wrong and I'll remove this answer, this is just off the top of my head.

Upvotes: 0

Related Questions