分享

Jetty嵌入项目式开发(把jetty发布到你的应用中)

 宇宙之窗 2014-04-29
Jetty/Tutorial/Embedding Jetty
Java代码 复制代码 收藏代码
  1. 这是来自Jetty官方的教程:(PS:我只是打酱油的)  
  2.   
  3. 使用以下示例,需要下载好 Jetty(独立版),(之前跑去下载eclpse版的结果不会用)  
  4.   
  5. ::::我用的是Jetty 7,跟Jetty 6相比,的确是因为多有点杂.  
  6.   
  7. 建议在使用以下实例的时候,将所下载的包(在jetty根目录的lib文件夹下)全部导入,有兴趣的可以一个一个导入试试,也可以根据错误,去查找哪个包有对应的类。Jetty7的分包已经很专业了,不怕看不懂  



=============================================================================
阅读注意:代码中的"jetty_home"为jetty在你电脑中的根目录,不要一味的复制,黏贴。
注意修改..
=============================================================================



Introduction
将Jetty发布到你的应用中,而不是把你的应用发布到Jetty应用服务器.
Jetty has a slogan "Don't deploy your application in Jetty, deploy Jetty in your application". What this means is that as an alternative to bundling your application as a standard WAR to be deployed in Jetty, Jetty is designed to be a software component that can be instantiated and used in a Java program just like any POJO.

This tutorial takes you step-by-step from the simplest Jetty server instantiation, to running multiple web applications with standards-based deployment descriptors.

The source for most of these examples is part of the standard Jetty project.
Details

嵌入式Jetty所需要做的事情
To embed a Jetty server, the following steps are typical:

   1. Create the server
   2. Add/Configure Connectors
   3. Add/Configure Handlers
   4. Add/Configure Servlets/Webapps to Handlers
   5. Start the server
   6. Wait (join the server to prevent main exiting).

Servers

The following code from SimplestServer.java will instantiate and run the simplest possible Jetty server:

Java代码 复制代码 收藏代码
  1. public class SimplestServer  
  2. {  
  3.     public static void main(String[] args) throws Exception  
  4.     {  
  5.         Server server = new Server(8080);  
  6.         server.start();  
  7.         server.join();  
  8.     }  
  9. }  


This runs a HTTP server on port 8080. It is not a very useful server as it has no handlers and thus will return a 404 error for every request.


Handlers

In order to produce a response to a request, Jetty requires a Handler to be set on the server. A handler may:

    * examine/modify the HTTP request.
    * generate the complete HTTP response.
    * call another Handler (see HandlerWrapper)
    * Select one or many Handlers to call (see [ http://download./jetty/stable-7/xref/org/eclipse/jetty/server/handler/HandlerCollection.html HandlerCollection]

Hello World Handler

The following code based on HelloHandler.java shows a simple hello world handler:

Java代码 复制代码 收藏代码
  1. public class HelloHandler extends AbstractHandler  
  2. {  
  3.     public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response)   
  4.         throws IOException, ServletException  
  5.     {  
  6.         response.setContentType("text/html;charset=utf-8");  
  7.         response.setStatus(HttpServletResponse.SC_OK);  
  8.         baseRequest.setHandled(true);  
  9.         response.getWriter().println("<h1>Hello World</h1>");  
  10.     }  
  11. }  

The parameters passed to the handle method are:

    * target - The target of the request which is either a URI or a name from a named dispatcher.
    * baseRequest -The Jetty mutable request object, which is always unwrapped.
    * request - The immutable request object, which may have been wrapped.
    * response - The response that may have been wrapped.

The handler sets the response status, content-type and marks the request as handled before it generates the body of the response using a writer.

The following code from OneHandler.java shows how this handler can be used by a Jetty server:

Java代码 复制代码 收藏代码
  1. public static void main(String[] args) throws Exception  
  2. {  
  3.     Server server = new Server(8080);  
  4.     server.setHandler(new HelloHandler());  
  5.    
  6.     server.start();  
  7.     server.join();  
  8. }  

You now know everything you need to know to write a HTTP server based on Jetty. However, complex request handling is typically built from multiple Handlers and we will look in later sections how handlers can be combined like aspects. Some of the handlers available in Jetty can be seen in the org.eclipse.jetty.server.handler package.
Connectors

In order to configure the HTTP connectors used by the server, one or more Connectors may be set on the server. Each connector may be configured with details such as interface, port, buffer sizes, timeouts etc.

The following code is based on ManyConnectors.java and shows how connectors may be set and configured for the Hello World example:
Java代码 复制代码 收藏代码
  1. public class ManyConnectors  
  2. {  
  3.     public static void main(String[] args) throws Exception  
  4.     {  
  5.         Server server = new Server();  
  6.    
  7.         SelectChannelConnector connector0 = new SelectChannelConnector();  
  8.         connector0.setPort(8080);  
  9.         connector0.setMaxIdleTime(30000);  
  10.         connector0.setRequestHeaderSize(8192);  
  11.    
  12.         SelectChannelConnector connector1 = new SelectChannelConnector();  
  13.         connector1.setHost("127.0.0.1");  
  14.         connector1.setPort(8888);  
  15.         connector1.setThreadPool(new QueuedThreadPool(20));  
  16.         connector1.setName("admin");  
  17.    
  18.         SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();  
  19.         String jetty_home =   
  20.           System.getProperty("jetty.home","../jetty-distribution/target/distribution");  
  21.         System.setProperty("jetty.home",jetty_home);  
  22.         ssl_connector.setPort(8443);  
  23.         ssl_connector.setKeystore(jetty_home + "/etc/keystore");  
  24.         ssl_connector.setPassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");  
  25.         ssl_connector.setKeyPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");  
  26.         server.addConnector(ssl_connector);  
  27.    
  28.         server.setConnectors(new Connector[]{ connector0, connector1, ssl_connector });  
  29.    
  30.         server.setHandler(new HelloHandler());  
  31.    
  32.         server.start();  
  33.         server.join();  
  34.     }  
  35. }  


Handler Collections, Wrappers and Scopes

Complex request handling is typically built from multiple Handlers that can be combined in various ways:

    * A Handler Collection holds a collection of other handlers and will call each handler in order. This is useful for combining statistics and logging handlers with the handler that generates the response.
    * A Handler List is a Handler Collection that calls each handler in turn until either an exception is thrown, the response is committed or the request.isHandled() returns true. It can be used to combine handlers that conditionally handle a request.
    * A Handler Wrapper is a handler base class that can be use to daisy chain handlers together in the style of aspect-oriented programming. For example, a standard web application is implemented by a chain of a context, session, security and servlet handlers.
    * A Context Handler Collection uses the longest prefix of the request URI (the contextPath) to select a specific ContextHandler to handle the request.

File Server

The following code from FileServer.java uses a HandlerList to combine the ResourceHandler with the DefaultHandler:

Java代码 复制代码 收藏代码
  1. public class FileServer  
  2. {  
  3.     public static void main(String[] args) throws Exception  
  4.     {  
  5.         Server server = new Server();  
  6.         SelectChannelConnector connector = new SelectChannelConnector();  
  7.         connector.setPort(8080);  
  8.         server.addConnector(connector);  
  9.    
  10.         ResourceHandler resource_handler = new ResourceHandler();  
  11.         resource_handler.setDirectoriesListed(true);  
  12.         resource_handler.setWelcomeFiles(new String[]{ "index.html" });  
  13.    
  14.         resource_handler.setResourceBase(".");  
  15.    
  16.         HandlerList handlers = new HandlerList();  
  17.         handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });  
  18.         server.setHandler(handlers);  
  19.    
  20.         server.start();  
  21.         server.join();  
  22.     }  
  23. }  


The resource handler is passed the request first and looks for a matching file in the local directory to serve. If a file is not found, then the request is passed to the default handler which will generate a 404 (or favicon.ico).
File Server with XML

Now is a good time to remind you that the Jetty XML configuration format is able to render simple Java code into XML configuration. So the above FileServer example can be written with a little reordering in Jetty XML as follows:

Java代码 复制代码 收藏代码
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www./jetty/configure.dtd">  
  3.    
  4. <Configure id="FileServer" class="org.eclipse.jetty.server.Server">  
  5.    
  6.     <Call name="addConnector">  
  7.       <Arg>  
  8.           <New class="org.eclipse.jetty.server.nio.SelectChannelConnector">  
  9.             <Set name="port">8080</Set>  
  10.           </New>  
  11.       </Arg>  
  12.     </Call>  
  13.    
  14.     <Set name="handler">  
  15.       <New class="org.eclipse.jetty.server.handler.HandlerList">  
  16.         <Set name="handlers">  
  17.       <Array type="org.eclipse.jetty.server.Handler">  
  18.         <Item>  
  19.           <New class="org.eclipse.jetty.server.handler.ResourceHandler">  
  20.             <Set name="directoriesListed">true</Set>  
  21.         <Set name="welcomeFiles">  
  22.           <Array type="String"><Item>index.html</Item></Array>  
  23.         </Set>  
  24.             <Set name="resourceBase">.</Set>  
  25.           </New>  
  26.         </Item>  
  27.         <Item>  
  28.           <New class="org.eclipse.jetty.server.handler.DefaultHandler">  
  29.           </New>  
  30.         </Item>  
  31.       </Array>  
  32.         </Set>  
  33.       </New>  
  34.     </Set>  
  35. </Configure>  

This XML file can be run from the FileServerXml.java class:

Java代码 复制代码 收藏代码
  1. public class FileServerXml  
  2. {  
  3.     public static void main(String[] args) throws Exception  
  4.     {  
  5.         Resource fileserver_xml = Resource.newSystemResource("fileserver.xml");  
  6.         XmlConfiguration configuration = new XmlConfiguration(fileserver_xml.getInputStream());  
  7.         Server server = (Server)configuration.configure();  
  8.         server.start();  
  9.         server.join();  
  10.     }  
  11. }  


File Server with spring

The Spring framework can also be used to assemble jetty servers. The file server example above can be written in spring configuration as:

Java代码 复制代码 收藏代码
  1. <beans>  
  2.   <bean id="Server" class="org.eclipse.jetty.server.Server" init-method="start" destroy-method="stop">  
  3.    
  4.     <property name="connectors">  
  5.       <list>  
  6.         <bean id="Connector" class="org.eclipse.jetty.server.nio.SelectChannelConnector">  
  7.           <property name="port" value="8080"/>  
  8.         </bean>  
  9.       </list>  
  10.     </property>  
  11.    
  12.     <property name="handler">  
  13.       <bean id="handlers" class="org.eclipse.jetty.server.handler.HandlerList">  
  14.         <property name="handlers">  
  15.           <list>  
  16.             <bean class="org.eclipse.jetty.server.handler.ResourceHandler">  
  17.               <property name="directoriesListed" value="true"/>  
  18.               <property name="welcomeFiles">  
  19.                 <list>  
  20.                   <value>index.html</value>  
  21.                 </list>  
  22.               </property>  
  23.               <property name="resourceBase" value="."/>  
  24.             </bean>         
  25.             <bean class="org.eclipse.jetty.server.handler.DefaultHandler"/>  
  26.           </list>  
  27.         </property>  
  28.       </bean>  
  29.     </property>  
  30.   </bean>  
  31. </beans>  


See also the Jetty Spring HOWTO.
Contexts

A ContextHandler is a HandlerWrapper that will respond only to requests that have a URI prefix that match the configured context path.

Requests that match the context path will have their path methods updated accordingly and the following optional context features applied as appropriate:

* A Thread Context classloader.
* A set of attributes
* A set init parameters
* A resource base (aka document root)
* A set of virtual host names

Requests that don't match are not handled.

The following code is based on OneContext.java and sets context path and classloader for the hello handler:

Java代码 复制代码 收藏代码
  1. public class OneContext  
  2. {  
  3.     public static void main(String[] args) throws Exception  
  4.     {  
  5.         Server server = new Server(8080);  
  6.    
  7.         ContextHandler context = new ContextHandler();  
  8.         context.setContextPath("/hello");  
  9.         context.setResourceBase(".");  
  10.         context.setClassLoader(Thread.currentThread().getContextClassLoader());  
  11.         server.setHandler(context);  
  12.    
  13.         context.setHandler(new HelloHandler());  
  14.    
  15.         server.start();  
  16.         server.join();  
  17.     }  
  18. }  


Servlets

Servlets are the standard way to provide application logic that handles HTTP requests. Servlets are like constrained Handlers with standard ways to map specific URIs to specific servlets. The following code is based on HelloServlet.java:

Java代码 复制代码 收藏代码
  1. public class HelloServlet extends HttpServlet  
  2. {  
  3.     private String greeting="Hello World";  
  4.     public HelloServlet(){}  
  5.     public HelloServlet(String greeting)  
  6.     {  
  7.         this.greeting=greeting;  
  8.     }  
  9.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  
  10.     {  
  11.         response.setContentType("text/html");  
  12.         response.setStatus(HttpServletResponse.SC_OK);  
  13.         response.getWriter().println("<h1>"+greeting+"</h1>");  
  14.         response.getWriter().println("session=" + request.getSession(true).getId());  
  15.     }  
  16. }  


ServletContext

A ServletContextHandler is a specialization of ContextHandler with support for standard servlets. The following code from OneServletContext shows 3 instances of the helloworld servlet registered with a ServletContextHandler:

Java代码 复制代码 收藏代码
  1. public class OneServletContext  
  2. {  
  3.     public static void main(String[] args) throws Exception  
  4.     {  
  5.         Server server = new Server(8080);  
  6.    
  7.         ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);  
  8.         context.setContextPath("/");  
  9.         server.setHandler(context);  
  10.    
  11.         context.addServlet(new ServletHolder(new HelloServlet()),"/*");  
  12.         context.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"/it/*");  
  13.         context.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"/fr/*");  
  14.    
  15.         server.start();  
  16.         server.join();  
  17.     }  
  18. }  


Web Application Context

A Web Applications context is a variation of ServletContextHandler that uses the standard layout and web.xml to configure the servlets, filters and other features:

Java代码 复制代码 收藏代码
  1. public class OneWebApp  
  2. {  
  3.     public static void main(String[] args) throws Exception  
  4.     {  
  5.         String jetty_home = System.getProperty("jetty.home","..");  
  6.    
  7.         Server server = new Server(8080);  
  8.    
  9.         WebAppContext webapp = new WebAppContext();  
  10.         webapp.setContextPath("/");  
  11.         webapp.setWar(jetty_home+"/webapps/test.war");  
  12.         server.setHandler(webapp);  
  13.    
  14.         server.start();  
  15.         server.join();  
  16.     }  
  17. }  


If during development, your application has not been assembled into a war file, then it can be run from its source components with something like:
Java代码 复制代码 收藏代码
  1. public class OneWebAppUnassembled  
  2. {  
  3.     public static void main(String[] args) throws Exception  
  4.     {  
  5.         Server server = new Server(8080);  
  6.    
  7.         WebAppContext context = new WebAppContext();  
  8.         context.setDescriptor(webapp+"/WEB-INF/web.xml");  
  9.         context.setResourceBase("../test-jetty-webapp/src/main/webapp");  
  10.         context.setContextPath("/");  
  11.         context.setParentLoaderPriority(true);  
  12.    
  13.         server.setHandler(context);  
  14.    
  15.         server.start();  
  16.         server.join();  
  17.     }  
  18. }  


Context Handler Collection

A Context Handler Collection uses the longest prefix of the request URI (the contextPath) to select a specific context. The following example combines the previous two examples in a single Jetty server:

Java代码 复制代码 收藏代码
  1. public class ManyContexts  
  2. {  
  3.     public static void main(String[] args) throws Exception  
  4.     {  
  5.         Server server = new Server(8080);  
  6.    
  7.         ServletContextHandler context0 = new ServletContextHandler(ServletContextHandler.SESSIONS);  
  8.         context0.setContextPath("/ctx0");  
  9.         server0.setHandler(context);  
  10.         context0.addServlet(new ServletHolder(new HelloServlet()),"/*");  
  11.         context0.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"/it/*");  
  12.         context0.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"/fr/*");  
  13.    
  14.         WebAppContext webapp = new WebAppContext();  
  15.         webapp.setContextPath("/ctx1");  
  16.         webapp.setWar(jetty_home+"/webapps/test.war");  
  17.    
  18.         ContextHandlerCollection contexts = new ContextHandlerCollection();  
  19.         contexts.setHandlers(new Handler[] { context0, webapp });  
  20.    
  21.         server.setHandler(contexts);  
  22.    
  23.         server.start();  
  24.         server.join();  
  25.     }  
  26. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多