2009-06-20 9 views
10

埋め込みJettyサーバが起動するサンプルコードを書いています。サーバは、正確に1つのサーブレットをロードするサーブレットにすべての要求を送信し、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); 
     } 

    } 

iは少ないコード/行と同じことを行うことができますか? (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

あなたは例えば、春のapplicationContext.xmlを宣言して桟橋を設定できます。

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

単にapplicationContext.xmlをからサーバーBeanを取得し、通話開始...私はそれはそれ1になり信じますコード行... :)

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

これは、Jettyの統合テストに役立ちます。

1

桟橋8で動作します。私はそれがはるかに簡単に桟橋を埋め込むことが可能ライブラリー、EasyJettyを、書いた

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

。 Jetty APIの上にある薄いレイヤーで、軽量です。

あなたの例では、次のようになります。

import com.athaydes.easyjetty.EasyJetty; 

public class Sample { 

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

} 
関連する問題