SECTION: 960-WebStart TITLE: Eclipse QUESTION: Can I embed Jetty in a Web Start application? Using Java Web Start to load an application has several advantages. The application can be launched from a link on a web page. The user only has to have Java installed. Updates are automatic. The application jars are downloaded and run locally so impact on the external web server is minimal and performance is good after the initial download.

Unfortunately there are a few disadvantages as well. The application must be packaged entirely in jar files, and the name and path to the jar files is not known ahead of time. If you embed a Jetty server in a JWS application, and want to serve static content, you must arrange for the server to be able to find the files. One solution is for the server to load the files from the classpath.

Here are the details:

A subclass of the Default servlet is used to serve the files. It is a very simple subclass, just overriding getResource() to get a resource. Here is the complete source:

    // ContentServlet.java
    package com.skillsoft.meccano.server;

    import java.io.IOException;
    import java.net.URL;

    import org.mortbay.jetty.servlet.Default;
    import org.mortbay.util.Resource;

    import com.skillsoft.meccano.util.ResourceLoader;

    /**
     * This servlet serves static resources from the classpath. It allows static resources to be bundled in a jar.
     *  <at> author Kent Johnson
     */
    public class ContentServlet extends Default {

        protected Resource getResource(String pathInContext) throws IOException {
            URL url = ResourceLoader.getResource(pathInContext);
            return Resource.newResource(url);
        }

    }

The actual resource loading is done in a separate module:

Here is ResourceLoader.getResource():

        public static URL getResource(String name) {
            if (name == null || name.length()==0)
                return null;

            return ResourceLoader.class.getResource(name);
        }

The ContentServlet is started just like any other servlet:

        context.addServlet("ContentServlet", "/*", "com.skillsoft.meccano.server.ContentServlet");

Note that this scheme exposes all of your classes to the webserver. If your server is widely available you might want to make the getResource() method more sophisticated in it's handling of resource requests.

[Contributed by Kent Johnson 29-Feb-2004]