How to configure static resources and custom services with integrated Jetty?

I am trying to configure a simple web service for my application by entering Jetty. I would like to have two different web services, a simple HTTP server that just serves static content (which will eventually become a GWT application) and a custom servlet that can issue JSON status messages for the application.

The structure of my mailing folder looks something like this:

+ dist/ - MyApp.jar + lib/ + html/ - index.html 

And here is what I still did to configure the embedded server. I get my test result correctly from my custom servlet when I visit http://localhost/data/ , but I cannot get DefaultServlet to find the index.html file.

 public Webserver(int port) { server = new Server(port); ServletContextHandler context = new ServletContextHandler(); context.setResourceBase("./html/"); server.setHandler(context); JsonDataApiServlet dataServlet = new JsonDataApiServlet(); DefaultServlet staticServlet = new DefaultServlet(); context.addServlet(new ServletHolder(dataServlet), "/data/*"); context.addServlet(new ServletHolder(staticServlet), "/*"); } 

It seems like this would be a common task for people embedding Jetty in things .. Am I even on the right track?

Edit

It turns out that this problem is caused by a misunderstanding of how relative paths are computed inside Jetty. I ran this from one folder above the dist folder using java -jar dist\MyApp.jar , and Jetty was looking for dist\..\html and not the correct dist\html . The problem with starting the jar from the dist folder. I will answer how I did this without having to run dist from the directory.

+7
source share
1 answer

As the editors say, it was just a problem with the directory from which I ran the bank. Here is the method I used to search the html folder from anywhere where the Jar was running:

First I added the html folder to the Jar Manifest Class-Path. The following code provides the html folder for wherever the Jar loads:

 ClassLoader loader = this.getClass().getClassLoader(); File indexLoc = new File(loader.getResource("index.html").getFile()); String htmlLoc = indexLoc.getParentFile().getAbsolutePath(); 

This uses Classloader to find the index file in the classpath, and then finds the absolute directory to go to Jetty:

 server = new Server(port); ServletContextHandler context = new ServletContextHandler(); context.setResourceBase(htmlLoc); context.setWelcomeFiles(new String[] { "index.html" }); server.setHandler(context); JsonDataApiServlet dataServlet = new JsonDataApiServlet(); DefaultServlet staticServlet = new DefaultServlet(); context.addServlet(new ServletHolder(dataServlet), "/data/*"); context.addServlet(new ServletHolder(staticServlet), "/*"); 
+6
source

All Articles