Static Content Alongside Jersey Services

2 minute read Published:

If you’ve worked with Jersey, you’re likely familiar with the embedded Grizzly server. Though I haven’t seen it mentioned often, Grizzly can indeed serve static content too. The following snippet is all that’s necessary to fire up an embedded web server. These examples were written with Grizzly 1.9.18-m and Jersey 1.4.

GrizzlyWebServer server = new GrizzlyWebServer(8080, "/var/www");

server.start();
...

While I’ve found some evidence that you should be able to just add a Jersey ServletAdapter to the Grizzly server, that doesn’t appear to work with current versions. Fortunately there are still a couple options that do work. If you want to serve both your static pages and Jersey services from the same context path, you can do something like the following. The key differences from a regular Jersey adapter are to specify the location to the static content in the ServletAdapter constructor, and you need to setHandleStaticResources to true.

GrizzlyWebServer server = new GrizzlyWebServer(8080);

ServletAdapter jerseyAdapter = new ServletAdapter("/var/www");
jerseyAdapter.addInitParameter("com.sun.jersey.config.property.packages",
                  "com.yourdomain");
jerseyAdapter.setContextPath("/");
jerseyAdapter.setServletInstance(new ServletContainer());
jerseyAdapter.setHandleStaticResources(true);

server.addGrizzlyAdapter(jerseyAdapter, new String[]{"/"});

server.start();
...

If you want to have different context paths for your static content and services, you can create two adapters like below.

GrizzlyWebServer server = new GrizzlyWebServer(8080);

ServletAdapter staticContentAdapter = new ServletAdapter("/var/www");
staticContentAdapter.setContextPath("/");
staticContentAdapter.setHandleStaticResources(true);

ServletAdapter jerseyAdapter = new ServletAdapter();
jerseyAdapter.addInitParameter("com.sun.jersey.config.property.packages",
                  "com.yourdomain");
jerseyAdapter.setContextPath("/ws");
jerseyAdapter.setServletInstance(new ServletContainer());

server.addGrizzlyAdapter(staticContentAdapter, new String[]{"/"});
server.addGrizzlyAdapter(jerseyAdapter, new String[]{"/ws"});

server.start();
...

One limitation to note is that this approach expects the files to be on the file system, which may not be what you’re looking for if you’re trying to create an executable jar type utility.