启动嵌入式Jetty服务器的最短代码

Pet*_*Mmm 12 java jetty embedded-jetty

我正在编写一些示例代码,其中启动了嵌入式Jetty服务器.服务器必须只加载一个servlet,将所有请求发送到servlet并监听localhost:80

我的代码到目前为止:

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);
        }

    }
Run Code Online (Sandbox Code Playgroud)

我可以用更少的代码/行来做同样的事情吗?(使用Jetty 6.1.0).

wor*_*ad3 13

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

删除了不必要的空格并内联了ServletHolder创建.那删除了5行.


Jon*_*Jon 5

您可以在Spring applicationcontext.xml中以声明方式配置Jetty,例如:

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

然后只需从applicationcontext.xml中检索服务器bean并调用start ...我相信它会使它成为一行代码然后...... :)

((Server)appContext.getBean("jettyServer")).start();
Run Code Online (Sandbox Code Playgroud)

它对涉及Jetty的集成测试很有用.