Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest code to start embedded Jetty server

I'm writing some example code where an embedded Jetty server is started. The server must load exactly one servlet, send all requests to the servlet and listen on localhost:80

My code so far:

static void startJetty() {
        try {
            Server server = new Server();

            Connector con = new SelectChannelConnector();
            con.setPort(80);
            server.addConnector(con);

            Context context = new Context(server, "/", Context.SESSIONS);
            ServletHolder holder = new ServletHolder(new MyApp());
            context.addServlet(holder, "/*");

            server.start();
        } catch (Exception ex) {
            System.err.println(ex);
        }

    }

Can i do the same with less code/lines ? (Jetty 6.1.0 used).

like image 254
PeterMmm Avatar asked Jun 20 '09 16:06

PeterMmm


2 Answers

static void startJetty() {
    try {
        Server server = new Server();
        Connector con = new SelectChannelConnector();
        con.setPort(80);
        server.addConnector(con);
        Context context = new Context(server, "/", Context.SESSIONS);
        context.addServlet(new ServletHolder(new MyApp()), "/*");
        server.start();
    } catch (Exception ex) {
        System.err.println(ex);
    }
}

Removed unnecessary whitespace and moved ServletHolder creation inline. That's removed 5 lines.

like image 80
workmad3 Avatar answered Oct 19 '22 23:10

workmad3


You could configure Jetty declaratively in a Spring applicationcontext.xml, e.g:

http://roopindersingh.com/2008/12/10/spring-and-jetty-integration/

then simply retrieve the server bean from the applicationcontext.xml and call start... I believe that makes it one line of code then... :)

((Server)appContext.getBean("jettyServer")).start();

It's useful for integration tests involving Jetty.

like image 31
Jon Avatar answered Oct 19 '22 23:10

Jon