Jetty入门

Posted Secondworld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jetty入门相关的知识,希望对你有一定的参考价值。

总述

同tomcat一样,jetty也是一个servlet引擎,jetty的神奇之处在于,jetty不仅可以作为一个web应用的容器,它甚至还可以作为一个程序中的插件来通过main函数加载web应用程序本身。

Jetty 是一个 Web server/servlet container, 支持 SPDY,WebSocket, OSGi, JMX,JNDI, JAAS 。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模块放到你的程序里。

 

整体架构

 

顶层类结构

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

 

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,来处理请求的不同方面。

 

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.

 

下载地址

http://www.eclipse.org/jetty/download.html

PS:默认的jetty相关配置文件都在etc路径下,其中端口和jetty相关组件的声明以及端口的配置在jetty.xml中,而web应用的默认描述配置为webdefault.xml。jetty可以像tomcat一样,将web应用放在webapps路径下启动,然后就可以直接访问,这个无需多说。下面就通过几个实例来详细讲解下jetty作为应用组件如何使用。

 

开发所需要的jar包

直接去jetty对应的lib目录下去取根目录下的所有jar包。

 

实例

 1 package com.rampage.midea.learn.jetty;
 2 import java.io.IOException;
 3 
 4 import javax.servlet.ServletException;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import javax.servlet.http.HttpSession;
 9 
10 import org.eclipse.jetty.server.Server;
11 import org.eclipse.jetty.server.SessionManager;
12 import org.eclipse.jetty.server.session.HashSessionManager;
13 import org.eclipse.jetty.server.session.SessionHandler;
14 import org.eclipse.jetty.servlet.ServletContextHandler;
15 import org.eclipse.jetty.servlet.ServletHolder;
16 import org.eclipse.jetty.webapp.WebAppContext;
17 
18 
19 
20 public class JettyTest {
21 
22     /**
23      * 通过ServletContextHandler来作为handler
24      * @throws Exception
25      */
26     public void addServletHandler1() throws Exception {
27         Server server = new Server(9090);                        
28         ServletContextHandler hand = new ServletContextHandler();
29         hand.addServlet(new ServletHolder(new HttpServlet() {     
30             private static final long serialVersionUID = 166145627009966144L;
31             public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
32                 response.setContentType("text/html;charset=utf-8");
33                 response.setStatus(HttpServletResponse.SC_OK);
34                 response.getWriter().println("<h1>Hello World</h1>");
35                 HttpSession s = req.getSession();
36                 String name = (String) s.getAttribute("name");
37                 response.getWriter().println("<h1>Session is:</h1>" + s + "," + name);
38                 response.getWriter().print("<br/>" + this.getServletContext().getRealPath("/"));
39             }
40         }), "/a");
41 
42         hand.addServlet(new ServletHolder(new HttpServlet() {
43             private static final long serialVersionUID = 8426818915524669191L;
44             public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
45                 response.setContentType("text/html;charset=utf-8");
46                 response.setStatus(HttpServletResponse.SC_OK);
47                 response.getWriter().println("<h1>Hello World!你好!</h1>");
48                 HttpSession s = req.getSession();
49                 s.setAttribute("name", "Jack");
50                 response.getWriter().print("<br/><a href=\'a\'>你好杰克!</a>");
51             }
52 
53         }), "/");
54         
55         // 设置内嵌的jetty支持session,默认情况下不支持session
56         SessionManager sm = new HashSessionManager();
57         hand.setSessionHandler(new SessionHandler(sm));
58         server.setHandler(hand);
59         server.start(); 
60         server.join();
61     }
62     
63     public static void main(String[] args) throws Exception {
64         new JettyTest().addServletHandler1();
65     }
66 
67 
68     
69     /**
70      * 通过WebAppContext的set方法指定web.xml地址和项目地址以及url    
71      * @throws Exception
72      */
73     public void projectHandler2() throws Exception {
74         String webapp = "D:\\\\programfiles\\\\MyEclipse10\\\\wk3\\\\day04\\\\WebRoot";
75         Server server = new Server(80); 
76         WebAppContext context = new WebAppContext(); 
77         context.setDescriptor(webapp + "/WEB-INF/web.xml");
78         context.setResourceBase(webapp);
79         context.setContextPath("/");
80         server.setHandler(context); 
81         server.start(); 
82         server.join();
83     }
84 
85     /**
86      * 直接再WebAppContext构造函数中传入项目路径和url上下文
87      * @throws Exception
88      */
89     public void projectHandler1() throws Exception {
90         String webapp = "D:\\\\WebRoot";
91         Server server = new Server(80);
92         WebAppContext context = new WebAppContext(webapp, "/abc");
93         server.setHandler(context);
94         server.start();
95         server.join();
96     }
97 }
JettyTest
 1 package com.rampage.midea.learn.jetty;
 2 import java.io.IOException;
 3 
 4 import javax.servlet.ServletException;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 public class HelloWorldServlet extends HttpServlet {
10     private static final long serialVersionUID = -4006259793736970043L;
11 
12     @Override
13     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
14             throws ServletException, IOException {
15         System.out.println("doGet");
16         resp.getWriter().write("hello world!");
17         resp.getWriter().close();
18     }
19 
20     @Override
21     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
22             throws ServletException, IOException {
23         System.out.println("doPost");
24         super.doPost(req, resp);
25     }
26 }
HelloWorldServlet

 

自定义server的一个实现

  1 package com.rampage.midea.learn.jetty;
  2 import java.io.FileInputStream;
  3 import java.io.FileNotFoundException;
  4 import java.io.IOException;
  5 
  6 import org.eclipse.jetty.server.Server;
  7 import org.eclipse.jetty.server.handler.ContextHandlerCollection;
  8 import org.eclipse.jetty.webapp.WebAppContext;
  9 import org.eclipse.jetty.xml.XmlConfiguration;
 10 import org.xml.sax.SAXException;
 11 
 12 public class JettyCustomServer extends Server {
 13     private String xmlConfigPath;
 14 
 15     private String contextPath;
 16 
 17     private String warPath;
 18 
 19     private String resourceBase = "./webapps";
 20 
 21     private String webXmlPath = "./webapps/WEB-INF/web.xml";
 22 
 23     public JettyCustomServer(String xmlConfigPath, String contextPath,
 24             String resourceBase, String webXmlPath) {
 25         this(xmlConfigPath, contextPath, resourceBase, webXmlPath, null);
 26     }
 27 
 28     public JettyCustomServer(String xmlConfigPath, String contextPath) {
 29         this(xmlConfigPath, contextPath, null, null, null);
 30     }
 31 
 32     public JettyCustomServer(String xmlConfigPath, String contextPath,
 33             String warPath) {
 34         this(xmlConfigPath, contextPath, null, null, warPath);
 35     }
 36 
 37     public JettyCustomServer(String xmlConfigPath, String contextPath,
 38             String resourceBase, String webXmlPath, String warPath) {
 39         super();
 40         if (StringUtils.isNotBlank(xmlConfigPath)) {
 41             this.xmlConfigPath = xmlConfigPath;
 42             readXmlConfig();
 43         }
 44 
 45         if (StringUtils.isNotBlank(warPath)) {
 46             this.warPath = warPath;
 47             if (StringUtils.isNotBlank(contextPath)) {
 48                 this.contextPath = contextPath;
 49                 applyHandle(true);
 50             }
 51         } else {
 52             if (StringUtils.isNotBlank(resourceBase))
 53                 this.resourceBase = resourceBase;
 54             if (StringUtils.isNotBlank(webXmlPath))
 55                 this.webXmlPath = webXmlPath;
 56             if (StringUtils.isNotBlank(contextPath)) {
 57                 this.contextPath = contextPath;
 58                 applyHandle(false);
 59             }
 60         }
 61 
 62     }
 63 
 64     private void readXmlConfig() {
 65         try {
 66             XmlConfiguration configuration = new XmlConfiguration(
 67                     new FileInputStream(this.xmlConfigPath));
 68             configuration.configure(this);
 69         } catch (FileNotFoundException e1) {
 70             e1.printStackTrace();
 71         } catch (SAXException e1) {
 72             e1.printStackTrace();
 73         } catch (IOException e1) {
 74             e1.printStackTrace();
 75         } catch (Exception e) {
 76             e.printStackTrace();
 77         }
 78     }
 79 
 80     public void applyHandle(Boolean warDeployFlag) {
 81 
 82         ContextHandlerCollection handler = new ContextHandlerCollection();
 83 
 84         WebAppContext webapp = new WebAppContext();
 85         webapp.setContextPath(contextPath);
 86         webapp.setDefaultsDescriptor("webdefault.xml");
 87 
 88         if (!warDeployFlag) {
 89             webapp.setResourceBase(resourceBase);
 90             webapp.setDescriptor(webXmlPath);
 91         } else {
 92             webapp.setWar(warPath);
 93         }
 94 
 95         handler.addHandler(webapp);
 96 
 97         super.setHandler(handler);
 98     }
 99 
100     public void startServer() {
101         try {
102             super.start();
103             System.out.println("current thread:"
104                     + super.getThreadPool().getThreads() + "| idle thread:"
105                     + super.getThreadPool().getIdleThreads());
106             super.join();
107         } catch (Exception e) {
108             e.printStackTrace();
109         }
110 
111     }
112 
113     public String getXmlConfigPath() {
114         return xmlConfigPath;
115     }
116 
117     public void setXmlConfigPath(String xmlConfigPath) {
118         this.xmlConfigPath = xmlConfigPath;
119     }
120 
121     public String getContextPath() {
122         return contextPath;
123     }
124 
125     public void setContextPath(String contextPath) {
126         this.contextPath = contextPath;
127     }
128 
129     public String getResourceBase() {
130         return resourceBase;
131     }
132 
133     public void setResourceBase(String resourceBase) {
134         this.resourceBase = resourceBase;
135     }
136 
137     public String getWebXmlPath() {
138         return webXmlPath;
139     }
140 
141     public void setWebXmlPath(String webXmlPath) {
142         this.webXmlPath = webXmlPath;
143     }
144 
145     public String getWarPath() {
146         return warPath;
147     }
148 
149     public void setWarPath(String warPath) {
150         this.warPath = warPath;
151     }
152 }
JettyCustomServer
 1 package com.rampage.midea.learn.jetty;
 2 
 3 public class JettyServerStart {
 4     public static void main(String[] args) {
 5         JettyCustomServer server = new JettyCustomServer(
 6                 "jetty.xml", "/");
 7         server.startServer();
 8 
 9     }
10 }
JettyServerStart

 

 

参考博客

 http://www.cnblogs.com/windlaughing/archive/2013/06/07/3125358.html

 

以上是关于Jetty入门的主要内容,如果未能解决你的问题,请参考以下文章

Jetty入门(1-2)配置Jetty - 独立运行模式

Jetty使用教程——开始使用Jetty

Jetty入门(1-4)

Jetty简介

推荐net开发cad入门阅读代码片段

jetty 必知必会