`
klcwt
  • 浏览: 190132 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Jetty入门

阅读更多

Starting Jetty

To start Jetty open a command shell, go to your Jetty installation directory, and type:

 

    java -jar start.jar

 

Jetty will not start if another process is using port 8080

    The port number can be changed by editing the $JETTY_HOME/etc/jetty.xml file. Please see the #Setting Jetty's Port section below or for more details see How to Configure Jetty. The rest of the instructions in this wiki will assume that you are using port 8080

 

 

 

 

Contents

[hide]
<script type="text/javascript"></script>

Introduction

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

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:

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
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println("<h1>Hello World</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 specialization 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();
    }
}

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();
    }
}
分享到:
评论

相关推荐

    jetty入门

    NULL 博文链接:https://jose-bing.iteye.com/blog/1240881

    Jetty入门学习资料

    Jetty 是一个开源的servlet容器,它为基于Java的web内容,例如JSP和servlet提供运行环境。Jetty是使用Java语言编写的,它的API以一组JAR包的形式发布。开发人员可以将Jetty容器实例化成一个对象,可以迅速为一些独立...

    jetty 入门实例

    jetty 超轻松入门,按步奏就可以学习,下载就可以运行

    Jetty中文手册

    Jetty入门(视频) 下载和安装Jetty 如何安装一个Jetty包 如何配置Jetty – 主要文档 如何运行Jetty 用JConsole监控Jetty 如何使用Jetty开发 Jetty HelloWorld教程 Jetty和Maven HelloWorld教程 Jetty(6)入门 ...

    jetty快速入门与嵌入使用

    jetty快速入门与嵌入使用,简单、易懂,轻松学习!

    Jetty Demo

    Hello Jetty 入门简单实例!可直接运行!

    jetty入门使用

    NULL 博文链接:https://smallbee.iteye.com/blog/1596501

    Jetty6入门教程

    资源名称:Jetty6入门教程资源截图: 资源太大,传百度网盘了,链接在附件中,有需要的同学自取。

    jetty6 嵌入式使用

    引入到eclipse可以直接使用Starter类运行。 包含必备jar包:jetty-6.1.26.jar,jetty-util-6.1.26,servlet的相关jar包。 jetty入门级源代码。

    jetty嵌入项目实战

    里面包含的有jetty嵌入开发的全部jar包,还有一个jetty实战项目,非常适合刚入门的童鞋观看

    Jetty 核心架构

    jetty7 核心架构 细致分析 入门到精通

    maven&struts2&jetty&tomcat

    该包适用于maven新手入门,因为作者本身也是一员maven新手,里面包括了maven的下载包,插件包,插件的配置,环境变量的设置,maven项目建立的详解及运行,里面集成了jetty,tomcat,struts2,当然还包括了直接运行jar包...

    jetty-seed:使用 Maven、Jetty 和 Jersey 的入门代码

    使用 Maven、Jetty 和 Jersey 的入门代码 使用 maven-shade-plugin 构建一个带有依赖项的胖 jar 使用单一资源在 8080 上运行码头服务器 建造 安装 跑步 java -jar target/jetty-app-{{version}}.jar 测试资源

    J2EE入门级指导书

    J2EE入门级指导书

    maven的入门使用

    maven入门使用 maven创建web项目 maven生成eclipse项目 maven+jetty的使用 jetty在eclipse的配置和使用

    JAX-RS入门jar包集合

    使用到的外部jar包有(必须的部分,需要... •jetty-io-7.5.4.v20111024.jar •jetty-server-7.5.4.v20111024.jar •jetty-util-7.5.4.v20111024.jar •jetty-continuation-7.5.4.v20111024.jar •wsdl4j-1.6.2.jar

    springmvn搭建的Maven项目入门

    本项目是SpringMVC框架入门配置 IDEA下搭建Maven项目,配置jetty服务,代码简单、完整。可以运行,做完入门的学习

    spring-mvc-test:spring-mvc 入门样例工程,可以导入jetty中运行

    spring-mvc-test spring-mvc 入门样例工程,可以导入jetty中运行

    Intellij Idea使用入门

    Intellij Idea使用入门,包括如何在web项目里集成maven、svn及使用jetty

Global site tag (gtag.js) - Google Analytics