Running a WAR as a Desktop Application
Join the DZone community and get the full member experience.Join For Free
If you have written a web application, the next logical step is to make it available offline. The long-term solution is clear: You give your web application an offline mode, which will hopefully be complemented by explicit application management in web browsers. Short- to mid-term, though, that is often not feasible, because the server provides crucial functionality to the client.
Thus, I was looking for a different solution. One option I had seen was Hudson’s self-executable WAR file: When you execute java -jar hudson.war, an embedded web server starts and you can immediately try out Hudson. This approach had two limitations that I didn’t like. First, I wanted my solution to be acceptable for end users, so I wanted a graphical user interface. Second, the embedded web server extracted the WAR file to a temporary directory and did so again for each startup, wasting time. In contrast, my solution does the following things:
- The application is a JAR file, the WAR is embedded inside. I opted against a single binary for JAR and WAR, because packaging the JAR as a nice desktop application adds platform-specific data, anyway, and makes it often impossible to deploy the result as a WAR.
- When the JAR starts up, a Swing user interface is shown. If this hasn’t been done before, the WAR file is extracted to a directory next to the JAR file. The idea is that there is a dedicated folder for the application in which the JAR resides. The location of the JAR is determined via this trick. The WAR file (=ZIP format) in the classpath is extracted to the file system using the standard Java API.
- Next, a web server is started and pointed to the web application directory in the file system (none of the web servers I’ve seen is able to serve a WAR file directly, let alone one that is embedded inside a JAR file). I used Winstone, because it is so small. There are even smaller ones, but those won’t allow you to use servlets. Obviously, any embeddable Java servlet container will do.
- A button allows the user to open the starting page of the web application in the default web browser. java.awt.Desktop (Java 6) allows you to do this. Currently, localhost and a fixed port is used. In the future, the port should be configurable and one could maybe automatically switch to a different port if the default one is occupied.
- Finally, I also produced a Mac OS X application. Such an application is a folder with the file name extension “.app” and the JAR file inside. This has the nice side effect of hiding the extracted WAR directory.
Opinions expressed by DZone contributors are their own.