You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

How to test using an embedded instance of Jetty6

This is a note to describe how to embed an instance of Jetty6 in order to test in the same way as the QuickStart project currently does using Jetty4.

The basic change involves replacing the code in the 'Start' class that passes the jetty-config.xml to the Jetty4 server with Java code that does the minimal setup required for Jetty 6, shown below...

With this change, the jetty-config.xml is no longer used - There many be a way of still passing a config file, but I'm not aware of it at the moment.

jettyServer = new Server();

SocketConnector conn = new SocketConnector();
conn.setPort(8080);
jettyServer.setConnectors(new Connector[]{conn});

WebAppContext wah = new WebAppContext();
wah.setContextPath("/myapp");
wah.setWar("src/main/webapp");
jettyServer.setHandler(wah);

jettyServer.start();

Just for completeness, that results in a 'Start' class as follows.<br>
(Feel free to replace the logger with your own preferred one, of course, or see https://simple-log.dev.java.net/ for more info on that one!)

package com.smarttrust.cd.mysp.tpm;

import org.grlea.log.SimpleLogger;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.webapp.WebAppContext;

public class Start {
    private static final SimpleLogger log = new SimpleLogger(Start.class);

    /**
     * Main function, starts the Jetty 6 server.
     *
     * @param args
     */
    public static void main(String[] args) {
        Server jettyServer = null;
        try {
            jettyServer = new Server();

            SocketConnector conn = new SocketConnector();
            conn.setPort(8080);
            jettyServer.setConnectors(new Connector[]{conn});

            WebAppContext wah = new WebAppContext();
            wah.setContextPath("/myapp");
            wah.setWar("src/main/webapp");
            jettyServer.setHandler(wah);

            jettyServer.start();
        }
        catch (Exception e) {
            log.fatal("Could not start the Jetty server: " + e);
            if (jettyServer != null) {
                try {
                    jettyServer.stop();
                }
                catch (Exception e1) {
                    log.fatal("Unable to stop the jetty server: " + e1);
                }
            }
        }
    }
}
  • No labels