Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add resources to Jetty programmatically

I have a main class that configures and fires up Jetty. (That's standard practice from Wicket for testing a webapp, but it's really not wicket-specific.)

final Server server = new Server();
//skipped socketconnector initialization

final WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/");
bb.setWar("src/main/webapp");
server.addHandler(bb);
server.start();

As you can see, src/main/webapp is used as webapp root. However, I have some resources that are in target/classes and that are copied to the webapp later. So I would like to add virtual directories to jetty.

I'd like to map target/classes/js to /js and target/classes/css to /css

Can anybody help?

BTW: it's jetty 6.1.4

like image 401
Sean Patrick Floyd Avatar asked Sep 15 '10 13:09

Sean Patrick Floyd


2 Answers

Add a WebAppContext for each virtual directory:

final Server server = new Server();
//skipped socketconnector initialization

final WebAppContext js = new WebAppContext();
js.setServer(server);
js.setContextPath("/js");
js.setWar("target/classes/js"); // or whatever the correct path is in your case
server.addHandler(js);

// css the same way

final WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/");
bb.setWar("src/main/webapp");
server.addHandler(bb);

server.start();
like image 74
Heri Avatar answered Nov 04 '22 11:11

Heri


For completeness, here's the workaround I have been using:

final Server server = new Server();
//skipped socketconnector initialization

final WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath("/");
bb.setWar("src/main/webapp");
final URL url = new File("target/classes").getAbsoluteFile().toURI().toURL();
final Resource resource = new FileResource(url);
final ResourceHandler handler = new ResourceHandler();
handler.setBaseResource(resource);
server.addHandler(handler);
server.addHandler(bb);
server.start();

But it's not very elegant, it mounts everything in target/classes and uses the webapp only as fallback.

like image 38
Sean Patrick Floyd Avatar answered Nov 04 '22 11:11

Sean Patrick Floyd