Jetty架構解析及應用示例


Jetty 是一個 Web server/servlet container, 支持 SPDY,WebSocketOSGiJMX,JNDIJAAS 。Jetty非常高效而且靈活,Google App Engine 選擇了Jetty,而放棄了Tomcat,或是其他的服務器。

Jetty has a slogan, "Don't deploy your application in Jetty, deploy Jetty in your application." What this means is that, putting an HTTP module into your application, rather than putting your application into an HTTP server.

Jetty的口號是:“不要把你的程序部署到Jetty里,而是把Jetty部署到你的程序里”,意味着,你可以把Jetty當成程序的一個HTTP模塊放到你的程序里。

本文先通過一個簡單的HelloWorld示例,展示了java應用中的Jetty是如何啟動的;接着詳細分析了Jetty的整體架構;最后展示了用Jetty啟動一個標准的Java web app。

Hello World 示例

需要的jar包:

jetty-server-8.1.11.v20130520.jar
javax.servlet-3.0.0.v201112011016.jar
jetty-continuation-8.1.11.v20130520.jar
jetty-http-8.1.11.v20130520.jar
jetty-io-8.1.11.v20130520.jar
jetty-util-8.1.11.v20130520.jar

HelloWorldHandler 類:

package edu.shao.jetty.sample;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

public class HelloWorldHandler extends AbstractHandler {
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getWriter().println("<h1>Hello World</h1>"); } }

MyServer 類:

package edu.shao.jetty.sample;

import org.eclipse.jetty.server.Server;

public class MyServer {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8081); 
        server.setHandler(new HelloWorldHandler()); 
        server.start(); 
        server.join();
    }
}

運行main()函數,在瀏覽器內輸入:http://localhost:8081/ 就可以看得結果。

 

Jetty架構

1、整體架構圖:

The Jetty Server is the plumbing between a collection of Connectors that accept HTTP connections, and a collection of Handlers that service requests from the connections and produce responses, with the work being done by threads taken from a thread pool.(The concept of a Servlet itself is implemented by a Servlet Handler.  you can build a Jetty server using only connectors and handlers, without using Servlets.)

2、頂層類結構:

受JSR77規范的啟發,Jetty的絕大多數的組件(Connector, Handler ,Buffer)都實現了LifeCycle接口。

3、Connectors:

The connectors represent the protocol handlers that accept connections, parse requests and generate responses. The different types of connectors available are based on the protocols, scheduling model and IO APIs used:

  1、SocketConnector - for few busy connections or when NIO is not available

  2、BlockingChannelConnector - for few busy connections when NIO is available

  3、SelectChannelConnector - for many mostly idle connections or asynchronous handling of Ajax requests

  4、SslSocketConnector - SSL without NIO

  5、SslSelectChannelConnector - SSL with non blocking NIO support

  6、AJPConnector - AJP protocol support for connections from apache mod_jk or mod_proxy_ajp

4、Handlers:

  

The Handler is the component that deals with received requests. Three styles of Handler: 

  1、Coordinating Handlers - Handlers that route requests to other handlers (eg HandlerCollection, ContextHandlerCollection)
  2、Filtering Handlers - Handlers that augment a request and pass it on to other handlers (eg. HandlerWrapper, ContextHandler, SessionHandler)
  3、Generating Handlers - Handlers that produce content (eg ResourceHandler and ServletHandler)

重點Handler:

  1、The ServletHandler is a Handler that generates content by passing the request to any configured Filters and then to a Servlet mapped by a URI pattern.

  2、A WebAppContext combines handlers for security, session and servlets in a single unit that can be configured with a web.xml descriptor.

你可以順序調用Handler,或者嵌套調用Handler,來處理請求的不同方面。

  

5、web應用

A WebAppContext supports the standardized layout of a web application and configuration of session, security, listeners, filter, servlets and JSP via a web.xml descriptor normally found in the WEB-INF directory of a webapplication.

 

把Jetty“部署”到Web應用中

1、開發時的部署示例:

這種部署方式還有一個誘人的特性:項目啟動后,如果某個類沒有被加載到內存中,對這個類的修改在下次該類被調用時就會生效,而不用重啟動項目;對JSP的修改,任何時候都會在下次被調用時生效,而不用重啟項目。這將給開發web應用帶來極大的便利。

1、這是用Maven構件的Java Web App項目,項目結構如下:

  

2、WebappStart 類:

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

public class WebappStart {

    public static void main(String[] args) throws Exception {
        Server server = new Server(8082);
         
        WebAppContext context = new WebAppContext();
        context.setResourceBase("./src/main/webapp");
        context.setDescriptor("./src/main/webapp/WEB-INF/web.xml");
        context.setContextPath("/test2");
        context.setParentLoaderPriority(true);
 
        server.setHandler(context);
 
        server.start();
        server.join();

    }

}

WebappStart類是整個項目的入口,運行此類,整個web項目就啟動了。

我們可以體驗到,把Jetty嵌入到Web項目中,作為Web Server,十分便利、靈活,並且相比其他服務器軟件要高效,是開發Web應用的首選WebServer。

 

2、用Jetty部署war包

我們在此示例中部署上面web工程的war包:TestWebApp2.war

 1、文件目錄的組織形式如下:

2、StartWar.java

import java.io.File;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

public class StartWar {

    public static void main(String[] args) throws Exception {
        String warPath= "E:/jetty/myapp/TestWebApp2.war";//war包的絕對地址
        String tempDir=new File(warPath).getParent();//war包所在的目錄,我們使用此目錄為臨時目錄

        Server server = new Server(8083);
         
        WebAppContext context = new WebAppContext();//構造Context Handler
        context.setWar(warPath);
        context.setTempDirectory(new File(tempDir));
        context.setContextPath("/test");
 
        server.setHandler(context);
        server.start();
        server.join();
    }
}

3、start.bat

前面是設置必要的變量,最后兩行分別是編譯StartWar.java類、運行StarWar.class。

@echo off
set directory=E:\jetty\
set java_dir=D:\Java\jdk1.6.0_35\
set classp=.;%java_dir%lib\dt.jar;%java_dir%lib\tools.jar;%directory%lib\*;

%java_dir%bin\javac -classpath %classp% StartWar.java
%java_dir%bin\java -classpath %classp% StartWar

4、此時控制台會顯示如下信息

此時已經部署完了,就是這么簡單

 

參考:

http://wiki.eclipse.org/Jetty/Tutorial

http://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM