`

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

阅读更多
Jetty/Tutorial/Embedding Jetty
这是来自Jetty官方的教程:(PS:我只是打酱油的)

使用以下示例,需要下载好 Jetty(独立版),(之前跑去下载eclpse版的结果不会用)

::::我用的是Jetty 7,跟Jetty 6相比,的确是因为多有点杂.

建议在使用以下实例的时候,将所下载的包(在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:

public class SimplestServer
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
        server.start();
        server.join();
    }
}


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.eclipse.org/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:

public class HelloHandler 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>");
    }
}

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:

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

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:
public class ManyConnectors
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server();
 
        SelectChannelConnector connector0 = new SelectChannelConnector();
        connector0.setPort(8080);
        connector0.setMaxIdleTime(30000);
        connector0.setRequestHeaderSize(8192);
 
        SelectChannelConnector connector1 = new SelectChannelConnector();
        connector1.setHost("127.0.0.1");
        connector1.setPort(8888);
        connector1.setThreadPool(new QueuedThreadPool(20));
        connector1.setName("admin");
 
        SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();
        String jetty_home = 
          System.getProperty("jetty.home","../jetty-distribution/target/distribution");
        System.setProperty("jetty.home",jetty_home);
        ssl_connector.setPort(8443);
        ssl_connector.setKeystore(jetty_home + "/etc/keystore");
        ssl_connector.setPassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
        ssl_connector.setKeyPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
        server.addConnector(ssl_connector);
 
        server.setConnectors(new Connector[]{ connector0, connector1, ssl_connector });
 
        server.setHandler(new HelloHandler());
 
        server.start();
        server.join();
    }
}


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:

public class FileServer
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server();
        SelectChannelConnector connector = new SelectChannelConnector();
        connector.setPort(8080);
        server.addConnector(connector);
 
        ResourceHandler resource_handler = new ResourceHandler();
        resource_handler.setDirectoriesListed(true);
        resource_handler.setWelcomeFiles(new String[]{ "index.html" });
 
        resource_handler.setResourceBase(".");
 
        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
        server.setHandler(handlers);
 
        server.start();
        server.join();
    }
}


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:

<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
 
<Configure id="FileServer" class="org.eclipse.jetty.server.Server">
 
    <Call name="addConnector">
      <Arg>
          <New class="org.eclipse.jetty.server.nio.SelectChannelConnector">
            <Set name="port">8080</Set>
          </New>
      </Arg>
    </Call>
 
    <Set name="handler">
      <New class="org.eclipse.jetty.server.handler.HandlerList">
        <Set name="handlers">
	  <Array type="org.eclipse.jetty.server.Handler">
	    <Item>
	      <New class="org.eclipse.jetty.server.handler.ResourceHandler">
	        <Set name="directoriesListed">true</Set>
		<Set name="welcomeFiles">
		  <Array type="String"><Item>index.html</Item></Array>
		</Set>
	        <Set name="resourceBase">.</Set>
	      </New>
	    </Item>
	    <Item>
	      <New class="org.eclipse.jetty.server.handler.DefaultHandler">
	      </New>
	    </Item>
	  </Array>
        </Set>
      </New>
    </Set>
</Configure>

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

public class FileServerXml
{
    public static void main(String[] args) throws Exception
    {
        Resource fileserver_xml = Resource.newSystemResource("fileserver.xml");
        XmlConfiguration configuration = new XmlConfiguration(fileserver_xml.getInputStream());
        Server server = (Server)configuration.configure();
        server.start();
        server.join();
    }
}


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:

<beans>
  <bean id="Server" class="org.eclipse.jetty.server.Server" init-method="start" destroy-method="stop">
 
    <property name="connectors">
      <list>
        <bean id="Connector" class="org.eclipse.jetty.server.nio.SelectChannelConnector">
          <property name="port" value="8080"/>
        </bean>
      </list>
    </property>
 
    <property name="handler">
      <bean id="handlers" class="org.eclipse.jetty.server.handler.HandlerList">
        <property name="handlers">
          <list>
            <bean class="org.eclipse.jetty.server.handler.ResourceHandler">
              <property name="directoriesListed" value="true"/>
              <property name="welcomeFiles">
                <list>
                  <value>index.html</value>
                </list>
              </property>
              <property name="resourceBase" value="."/>
            </bean>       
            <bean class="org.eclipse.jetty.server.handler.DefaultHandler"/>
          </list>
        </property>
      </bean>
    </property>
  </bean>
</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:

public class OneContext
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
 
        ContextHandler context = new ContextHandler();
        context.setContextPath("/hello");
        context.setResourceBase(".");
        context.setClassLoader(Thread.currentThread().getContextClassLoader());
        server.setHandler(context);
 
        context.setHandler(new HelloHandler());
 
        server.start();
        server.join();
    }
}


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:

public class HelloServlet extends HttpServlet
{
    private String greeting="Hello World";
    public HelloServlet(){}
    public HelloServlet(String greeting)
    {
        this.greeting=greeting;
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println("<h1>"+greeting+"</h1>");
        response.getWriter().println("session=" + request.getSession(true).getId());
    }
}


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:

public class OneServletContext
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
 
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
 
        context.addServlet(new ServletHolder(new HelloServlet()),"/*");
        context.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"/it/*");
        context.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"/fr/*");
 
        server.start();
        server.join();
    }
}


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:

public class OneWebApp
{
    public static void main(String[] args) throws Exception
    {
        String jetty_home = System.getProperty("jetty.home","..");
 
        Server server = new Server(8080);
 
        WebAppContext webapp = new WebAppContext();
        webapp.setContextPath("/");
        webapp.setWar(jetty_home+"/webapps/test.war");
        server.setHandler(webapp);
 
        server.start();
        server.join();
    }
}


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:
public class OneWebAppUnassembled
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
 
        WebAppContext context = new WebAppContext();
        context.setDescriptor(webapp+"/WEB-INF/web.xml");
        context.setResourceBase("../test-jetty-webapp/src/main/webapp");
        context.setContextPath("/");
        context.setParentLoaderPriority(true);
 
        server.setHandler(context);
 
        server.start();
        server.join();
    }
}


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:

public class ManyContexts
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
 
        ServletContextHandler context0 = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context0.setContextPath("/ctx0");
        server0.setHandler(context);
        context0.addServlet(new ServletHolder(new HelloServlet()),"/*");
        context0.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"/it/*");
        context0.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"/fr/*");
 
        WebAppContext webapp = new WebAppContext();
        webapp.setContextPath("/ctx1");
        webapp.setWar(jetty_home+"/webapps/test.war");
 
        ContextHandlerCollection contexts = new ContextHandlerCollection();
        contexts.setHandlers(new Handler[] { context0, webapp });
 
        server.setHandler(contexts);
 
        server.start();
        server.join();
    }
}
分享到:
评论

相关推荐

    jetty8+ 内嵌式启动运行demo

    内嵌式Web服务器是将Web服务器功能直接整合到你的应用程序代码中的方式,而不是单独部署一个Web服务器。这样,你可以直接启动你的Java应用程序,并且Web服务也随之启动,无需额外配置。 在Jetty 8中,我们主要会...

    jetty1.3.3

    4. **嵌入式能力**:Jetty 的一大优势是它可以轻松地嵌入到其他 Java 应用程序中,无需单独部署或管理服务器进程。 5. **线程模型**:Jetty 使用高效的线程模型来处理并发请求,确保高并发场景下的性能和稳定性。 ...

    jetty-all-8.2.0.v20160908.zip

    【标题】"jetty-all-8.2.0.v20160908.zip" 是一个包含...通过深入研究这个压缩包的内容,开发者不仅可以提升对Jetty和Scala的理解,还能掌握Web开发的最佳实践,以及如何参与到开源项目中,增强自身的软件工程技能。

    Java Web应用开发项目教程[聂明][电子教案].rar

    《Java Web应用开发项目教程》是由专家聂明编写的,主要针对希望深入理解和掌握Java Web技术的开发者。这本书以项目实战的方式,系统地讲解了如何使用Java语言进行Web应用程序的开发,涵盖了从基础到高级的各种知识...

    Java Web项目开发案例精粹14新闻发布系统源码.rar

    7. **部署与容器**:开发完成后,这个Java Web项目通常会被打包成WAR文件,部署到像Tomcat、Jetty或WebLogic这样的Java应用服务器上运行。 8. **版本控制与构建工具**:在开发过程中,版本控制工具如Git用于协同...

    《J2EE专业项目实例开发》源代码

    6. **Spring框架**:Spring是一个全面的Java企业级应用开发框架,提供依赖注入(DI)、面向切面编程(AOP)、事务管理等功能。Spring MVC是Spring框架的一部分,用于构建Web应用。此外,Spring还提供了集成其他技术...

    JAVA农业网项目(jsp)

    6. **Web服务器**:项目可能使用了Tomcat、Jetty等常见的Java Web服务器来运行JSP应用。这些服务器负责解析JSP文件并生成HTML,然后发送给客户端浏览器。 7. **安全考虑**:任何网站都必须关注安全性,例如防止SQL...

    jsf-jetty:这是一个JSF Web项目,内嵌了Jetty服务器;

    它不依赖于任何特定的应用服务器,可以独立运行或嵌入到其他Java应用中。Jetty以其小巧、快速和易于配置而闻名,常被用于测试、原型设计以及那些不需要完整应用服务器功能的项目。 在标题和描述中提到的 "jsf-jetty...

    javaweb项目文件.zip_javaweb_javaweb项目_javaweb项目开发_racea3s

    JavaWeb项目是一个基于Java技术构建的Web应用程序,用于创建交互式的网页应用。在这个"javaweb项目文件.zip_javaweb_javaweb项目_javaweb项目开发_racea3s"压缩包中,我们看到它包含了一个名为"jspbbs"的子文件,这...

    web项目开发必备小软件

    在Web项目开发中,高效的工具集是至关重要的,它们能够帮助开发者提高生产力,减少出错的可能性,以及更快地实现功能。下面将详细讲解与标题"web项目开发必备小软件"和描述相关的知识点,并重点关注标签中提及的asp...

    jsp项目开发实例!!!!!!!!!!!!!

    在这个“jsp项目开发实例”中,我们将深入探讨JSP的核心概念、开发流程以及相关工具的使用。 1. **JSP基本概念** - **JSP页面结构**:JSP页面由静态内容(HTML、CSS、JavaScript)和动态元素(Java代码)组成,...

    北大青鸟ACCP5.0_S2(下)使用JSP开发Web应用系统(JSP)

    【北大青鸟ACCP5.0_S2(下)使用JSP开发Web应用系统】是北大青鸟教育机构推出的Web开发课程,旨在帮助学员掌握基于Java的JSP(JavaServer Pages)技术,用于构建动态、交互式的Web应用程序。本课程分为指导练习和在线...

    Java Web 项目开发案例精粹 6

    在本Java Web项目开发案例中,我们关注的是一个名为"报价管理系统"的应用程序。这个系统是基于Java Web技术实现的,旨在帮助企业高效...通过深入分析和理解这个案例,开发者能进一步提升在Web应用开发领域的专业技能。

    web project中手动嵌入birt运行支持 2.5.2, 3.7.2

    在IT行业中,Web项目开发经常会遇到需要生成报告的需求,BIRT(Business Intelligence and Reporting Tools)是一种开源的报表系统,能够帮助开发者在Web应用中轻松实现数据可视化和报表生成。本主题将详细介绍如何...

    java Web项目开发

    Java Web项目开发主要涉及到Web应用程序的设计与实现,通常包括前端用户界面、后端服务器逻辑以及数据库交互等组件。在这个特定的压缩包中,有两个Web项目,分别是在线图书购买和在线答疑系统,它们都是基于Java技术...

    实战突击 JavaWeb 项目整合开发2

    《实战突击 JavaWeb 项目整合开发2》的源码提供了丰富的学习材料,旨在帮助开发者深入理解和实践JavaWeb的综合应用。这个压缩包被分为8个部分,以方便管理和下载,确保了大型项目的有序性。 JavaWeb是Java技术在Web...

    基于 Servlet 开发的房屋发布系统.zip

    Servlet是Java Web开发中的核心组件,它允许开发者创建动态、交互式的Web应用程序。 【相关知识点】 1. **Servlet基础**:Servlet是Java编程语言中用来扩展服务器功能的接口,它不是具体的类,而是一系列接口的...

    J2EE前端应用程式架构与

    【Struts Framework】是由Craig McClanahan在2000年提出的,于2001年6月发布了1.0版本,现托管于Apache Jakarta项目中。Struts是一个基于MVC(Model-View-Controller)架构模式的Web应用程序框架,它封装了开发Web...

    基于javaweb开发的新闻网

    这个项目可能包含了从用户界面设计、后端服务处理到数据库交互的全方位开发工作,为用户提供了一个浏览、搜索和分享新闻的功能丰富的平台。下面将详细探讨JavaWeb开发中的关键知识点。 1. **Servlet与JSP**:在...

    jsp&servlet应用开发借鉴.pdf

    **JSP&Servlet应用开发借鉴** 在Web开发领域,Java Server Pages (JSP) 和Servlet是两种关键的技术,常用于构建动态、交互式的Web应用程序。本文将深入探讨这两个技术,并提供一些开发应用的实践指导。 **一、JSP...

Global site tag (gtag.js) - Google Analytics