users@grizzly.java.net

Serving static files with CLStaticHttpHandler

From: Christian Helmbold <christian.helmbold_at_yahoo.de>
Date: Wed, 12 Jun 2013 14:07:58 +0100 (BST)

Hi,

I want to serve static files which are under target/classes/templates in my maven project structure or in the corresponding .jar file. I need both options, because I want to serve the files during development (where I don't package .jars) and during production.

I tried it like this: 

  server.getServerConfiguration().addHttpHandler(
    new CLStaticHttpHandler(Main.class.getClassLoader()), "/static");

But if I look at the source code I'm missing an option to set a base path. The request URI is used directly to look up the resource starting in the root directory of the class loader: https://github.com/GrizzlyNIO/grizzly-mirror/blob/2.3.x/modules/http-server/src/main/java/org/glassfish/grizzly/http/server/CLStaticHttpHandler.java#L106

If I use the StaticHttpHandler like this:

  server.getServerConfiguration().addHttpHandler(

    new StaticHttpHandler(getTemplatePath()), "/static");

  // ...

  private static String getTemplatePath() throws URISyntaxException {
    return Main.class.getClassLoader().getResource("templates/static").getPath();
  }

everything works as expected, as long as I'm not running the application as a jar.

How can I serve static files from the file system and from within a .jar with Grizzly?

Thanks,
Christian