Welcome

Running Jetty Embedded

While I was playing with JSFUnit, I just needed to start a web container inside my tests. Jettyis very famous as being embeddable in standalone java applications. Therefore, spots are directed onto Jetty web site, and I downloaded latest stable version and started playing with it.

First you need to add servlet.jar, jetty.jar, jetty-util.jar and start.jar are needed in your classpath to run jetty.

After that, create a new server instance and a Connector to answer HTTP requests from a specific port.

Server server = new Server();
SelectChannelConnector connector=new SelectChannelConnector();
connector.setPort(Integer.getInteger("jetty.port",8088).intValue());
server.setConnectors(new Connector[]{connector});

Connector needs to call a Handler for each request received. Therefore we need to create and add a Handler to server instance. WebAppContext is a special Handler instance to start your web application.

WebAppContext webapp = new WebAppContext();
webapp.setParentLoaderPriority(true);
webapp.setContextPath("/myproject");
webapp.setWar("d:/work/projects/myproject/WebContent");
webapp.setDefaultsDescriptor("d:/work/projects/myproject/webdefault.xml");
server.setHandler(webapp);

webdefault.xml of jetty can be found in its distribution bundle under etc directory.

Finally, we can run our server;

server.start();

If we want jetty’s thread pool to be blocked until LifeCycle objects are stopped, then we just need to call server’s join method.

server.join();

In order to stop your server when you finished with it, call its stop method.

server.stop();

That’s all…

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.