RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Embedded Jetty and Spring: The Lightweight Antidote for Java EE Complexity : Page 2

Enterprise Java development does not need to be heavyweight and Ant-driven; with embedded Jetty and Spring, it can be lean, mean, fast, and—above all—productive.


Setting Up Eclipse for Development

You can set up embedded Jetty in a variety of ways, but this is the way I do it most of the time:
  1. Create a separate Eclipse Java project for the main server. Add the Jetty and Spring JARs as external JARs to make them accessible to the server. Also, create three folders underneath the main project folder:
    • etc: This is where all the config files will go.
    • logs: This is where Jetty will place its log files.
    • webapps: This is a dummy directory that Jetty needs just to start up.
  2. Copy the jetty.xml config file from your Jetty/etc folder into the project's /etc folder. This will allow you to control the characteristics of your Jetty server (e.g., web port, number of threads, and so on).

Your main server project should look something like Figure 1 after being set up. Remember to make all the third-party JARs available to other projects by exporting them in the project's build properties configuration (see Figure 2).

Figure 1. A Configured Embedded Jetty Server Project: Your main server project should look something like this.
Figure 2. Exported Jetty and Spring JARs: Make all the third-party JARs available to other projects.

The Main Server Class

Your main server class (effectively the main() method of your application) is a thin layer responsible only for starting and configuring Jetty. I usually prefer to keep the actual application in a separate project. That way, the application is independent of embedded Jetty and I can build it as a regular WAR and deploy it to a standalone Jetty instance later for QA or production.

Here is the minimal code required for a typical embedded Jetty start up:

Server jetty = new Server();
String[] configFiles = {"etc/jetty.xml"};
for(String configFile : configFiles) {
   XmlConfiguration configuration = new XmlConfiguration(new File(configFile).toURI().toURL()); 

That's it! The best part is that running this code makes Jetty start up in less than one second (on my machine). Starting and stopping your application is much faster than re-deploying a WAR could ever be, and it makes enterprise/web development in Java as easy as developing a regular application.

Open up your browser and point it to localhost:8080 and you should see a message from Jetty informing you that it's running. However, it won't have any contexts configured. That comes next.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date