Grizzly 2.3.3: Serving Static HTTP Resources from Jar Files

Besides SPDY updates and SPDY server push support, Grizzly 2.3.3 is coming with another interesting feature – possibility to serve static HTTP resources from jar files, or to be more precise serving static HTTP resources using Java ClassLoader.

As we remember it was always easy to register Grizzly StaticHttpHandler to serve HTTP resources from the specific file system path or even several paths.

For example in order to serve static HTTP resources from “/Users/myhome/mypages” folder we can register StaticHttpHandler like:

StaticHttpHandler staticHttpHandler = new StaticHttpHandler("/Users/myhome/mypages/");
server.getServerConfiguration().addHttpHandler(staticHttpHandler, "/");

But we got many questions from users asking: “What if I have static resources in a jar file?” True, the entire standalone server plus static resources might be bundled to a single jar file, so how to serve these resources?

In Grizzly 2.3.3 we implemented new CLStaticHttpHandler, which is able to serve static HTTP resources using Java ClassLoader.

For example, if our standalone server and static HTTP resources are bundle to a single jar file, the CLStaticHttpHandler might be registered like:

public class StandaloneServer {
    public static void main(String[] args) throws IOException {
        HttpServer httpServer = new HttpServer();
        NetworkListener listener = new NetworkListener("grizzly", "0.0.0.0", 9999);
        httpServer.addListener(listener);

        httpServer.getServerConfiguration().addHttpHandler(
                new CLStaticHttpHandler(StandaloneServer.class.getClassLoader()), "/");

        try {
            httpServer.start();

            System.out.println("Press enter to stop");
            System.in.read();
        } finally {
            httpServer.stop();
        }
    }
}

Or, if we have our static HTTP resources in a separate jar file, that is not on the application class path – the sample above should be changed like:

httpServer.getServerConfiguration().addHttpHandler(
        new CLStaticHttpHandler(new URLClassLoader(new URL[] {new URL("file:///Users/myhome/mypages/static-pages.jar")})), "/");

If you have any question – don’t hesitate to ask on Grizzly mailing lists.

Advertisements
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s