2009-06-20 73 views
10

我正在編寫一些嵌入式Jetty服務器啓動的示例代碼。服務器必須加載只有一個servlet中,發送到servlet的所有請求,並聽取在localhost:80啓動嵌入式Jetty服務器的最短代碼

我迄今爲止代碼:

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

    } 

我可以做同樣的用更少的代碼/行? (使用Jetty 6.1.0)。

回答

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

刪除了不必要的空白並移動了ServletHolder內聯創建。這刪除了5行。

5

你可以聲明在Spring的applicationContext.xml配置碼頭,如:

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

然後簡單地檢索來自applicationContext.xml中的服務器豆和呼叫開始......我相信,它使一個行代碼,然後... :)

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

它涉及碼頭集成測試非常有用。

1

工程與碼頭8:

import org.eclipse.jetty.server.Server; 
import org.eclipse.jetty.webapp.WebAppContext; 

public class Main { 
    public static void main(String[] args) throws Exception { 
      Server server = new Server(8080); 
      WebAppContext handler = new WebAppContext(); 
      handler.setResourceBase("/"); 
      handler.setContextPath("/"); 
      handler.addServlet(new ServletHolder(new MyApp()), "/*"); 
      server.setHandler(handler); 
      server.start(); 
    } 
} 
1
 Server server = new Server(8080); 
     Context root = new Context(server, "/"); 
     root.setResourceBase("./pom.xml"); 
     root.setHandler(new ResourceHandler()); 
     server.start(); 
2

我寫了一個庫,EasyJetty,這使得它更容易嵌入碼頭。它只是Jetty API上方的一個薄層,非常輕便。

你的榜樣應該是這樣的:

import com.athaydes.easyjetty.EasyJetty; 

public class Sample { 

    public static void main(String[] args) { 
     new EasyJetty().port(80).servlet("/*", MyApp.class).start(); 
    } 

}