Difference between revisions of "Jetty/Tutorial/Embedding Jetty"

From Eclipsepedia

Jump to: navigation, search
Line 1: Line 1:
 
{{Jetty Tutorial
 
{{Jetty Tutorial
| introduction = Jetty has a slogan "Don't deploy your application in Jetty, deploy Jetty in your application". What this means is that Jetty 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 [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJO].  
+
| 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 [http://en.wikipedia.org/wiki/Plain_Old_Java_Object POJO].  
  
This tutorial takes you step by step from the simplest jetty server instantiation, through programmatically, to running multiple web applications with standards based deployment descriptors.
+
This tutorial takes you step-by-step from the simplest Jetty server instantiation, to running multiple web applications with standards-based deployment descriptors.
  
The [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/package-summary.html source] for most of these examples is part of the standard jetty project.
+
The [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/package-summary.html source] for most of these examples is part of the standard Jetty project.
  
 
| details =  
 
| details =  
Line 17: Line 17:
 
== Servers ==
 
== Servers ==
 
The following code from [http://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk/example-jetty-embedded/src/main/java/org/eclipse/jetty/embedded/SimplestServer.java SimplestServer.java] will instantiate and run the simplest possible Jetty server:
 
The following code from [http://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk/example-jetty-embedded/src/main/java/org/eclipse/jetty/embedded/SimplestServer.java SimplestServer.java] will instantiate and run the simplest possible Jetty server:
<pre>
+
<source lang="java">
 
public class SimplestServer
 
public class SimplestServer
 
{
 
{
Line 27: Line 27:
 
     }
 
     }
 
}
 
}
</pre>
+
</source>
  
This runs a HTTP server on port 8080.  It is not a very useful server as it has not handlers and thus will return a 404 error for every request.
+
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 ==
 
== Handlers ==
In order to produce a response to a request, Jetty requires a [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/xml/XmlParser.html Handler] to be set on the server.  A handler may:
+
In order to produce a response to a request, Jetty requires a [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/Handler.html Handler] to be set on the server.  A handler may:
 
* examine/modify the HTTP request.
 
* examine/modify the HTTP request.
 
* generate the complete HTTP response.
 
* generate the complete HTTP response.
 
* call another Handler (see [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/HandlerWrapper.html HandlerWrapper])
 
* call another Handler (see [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/HandlerWrapper.html 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]
 
* 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 ===
 
=== Hello World Handler ===
 
The following code based on [http://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk/example-jetty-embedded/src/main/java/org/eclipse/jetty/embedded/HelloHandler.java HelloHandler.java] shows a simple hello world handler:
 
The following code based on [http://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk/example-jetty-embedded/src/main/java/org/eclipse/jetty/embedded/HelloHandler.java HelloHandler.java] shows a simple hello world handler:
<pre>public class HelloHandler extends AbstractHandler
+
<source lang="java">public class HelloHandler extends AbstractHandler
 
{
 
{
 
     public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response)  
 
     public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response)  
Line 53: Line 52:
 
     }
 
     }
 
}
 
}
</pre>
+
</source>
  
 
The parameters passed to the handle method are:
 
The parameters passed to the handle method are:
Line 64: Line 63:
  
 
The following code from [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/OneHandler.html OneHandler.java] shows how this handler can be used by a Jetty server:
 
The following code from [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/OneHandler.html OneHandler.java] shows how this handler can be used by a Jetty server:
<pre>
+
<source lang="java">
 
public static void main(String[] args) throws Exception
 
public static void main(String[] args) throws Exception
 
{
 
{
Line 73: Line 72:
 
     server.join();
 
     server.join();
 
}
 
}
</pre>
+
</source>
  
 
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 [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/package-frame.html org.eclipse.jetty.server.handler] package.
 
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 [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/package-frame.html org.eclipse.jetty.server.handler] package.
Line 80: Line 79:
 
In order to configure the HTTP connectors used by the server, one or more [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/Connector.html Connector]s may be set on the server. Each connector may be configured with details such as interface, port, buffer sizes, timeouts etc.
 
In order to configure the HTTP connectors used by the server, one or more [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/Connector.html Connector]s 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 [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/ManyConnectors.html ManyConnectors.java] and shows how connectors may be set and configured for the Hello world example:
+
The following code is based on [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/ManyConnectors.html ManyConnectors.java] and shows how connectors may be set and configured for the Hello World example:
<pre>
+
<source lang="java">
 
public class ManyConnectors
 
public class ManyConnectors
 
{
 
{
Line 117: Line 116:
 
     }
 
     }
 
}
 
}
</pre>
+
</source>
  
== Handler Collections, wrappers and Scopes ==
+
== Handler Collections, Wrappers and Scopes ==
  
 
Complex request handling is typically built from multiple Handlers that can be combined in various ways:
 
Complex request handling is typically built from multiple Handlers that can be combined in various ways:
 
* A [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/HandlerCollection.html 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 [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/HandlerCollection.html 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 [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/HandlerList.html 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 [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/HandlerList.html 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 [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/HandlerWrapper.html 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 [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/HandlerWrapper.html 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 [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/ContextHandlerCollection.html Context Handler Collection] uses the longest prefix of the request URI (the contextPath) to select a specific [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/ContextHandler.html ContextHandler] to handle the request.  
 
* A [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/ContextHandlerCollection.html Context Handler Collection] uses the longest prefix of the request URI (the contextPath) to select a specific [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/ContextHandler.html ContextHandler] to handle the request.  
  
Line 130: Line 129:
  
 
The following code from [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/FileServer.html FileServer.java] uses a HandlerList to combine the [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/ResourceHandler.html ResourceHandler] with the [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/DefaultHandler.html DefaultHandler]:
 
The following code from [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/FileServer.html FileServer.java] uses a HandlerList to combine the [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/ResourceHandler.html ResourceHandler] with the [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/DefaultHandler.html DefaultHandler]:
<pre>
+
<source lang="java">
 
public class FileServer
 
public class FileServer
 
{
 
{
Line 154: Line 153:
 
     }
 
     }
 
}
 
}
</pre>
+
</source>
  
 
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).
 
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).
  
Now is a good time to remind you that the [[/Jetty/Reference/jetty.xml_syntax|Jetty XML]] configuration format is able to render simple java code into XML configuration.  So the FileServer example could be written in with a little reordering in jetty XML as follows:
+
Now is a good time to remind you that the [[Jetty/Reference/jetty.xml syntax|Jetty XML]] configuration format is able to render simple Java code into XML configuration.  So the FileServer example could be written with a little reordering in Jetty XML as follows:
<pre>
+
<source lang="xml">
&lt;?xml version="1.0"?>
+
<?xml version="1.0"?>
&lt;!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
+
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
  
&lt;Configure id="FileServer" class="org.eclipse.jetty.server.Server">
+
<Configure id="FileServer" class="org.eclipse.jetty.server.Server">
  
     &lt;Call name="addConnector">
+
     <Call name="addConnector">
       &lt;Arg>
+
       <Arg>
           &lt;New class="org.eclipse.jetty.server.nio.SelectChannelConnector">
+
           <New class="org.eclipse.jetty.server.nio.SelectChannelConnector">
             &lt;Set name="port">8080&lt;/Set>
+
             <Set name="port">8080</Set>
           &lt;/New>
+
           </New>
       &lt;/Arg>
+
       </Arg>
     &lt;/Call>
+
     </Call>
  
     &lt;Set name="handler">
+
     <Set name="handler">
       &lt;New class="org.eclipse.jetty.server.handler.HandlerList">
+
       <New class="org.eclipse.jetty.server.handler.HandlerList">
         &lt;Set name="handlers">
+
         <Set name="handlers">
  &lt;Array type="org.eclipse.jetty.server.Handler">
+
  <Array type="org.eclipse.jetty.server.Handler">
    &lt;Item>
+
    <Item>
      &lt;New class="org.eclipse.jetty.server.handler.ResourceHandler">
+
      <New class="org.eclipse.jetty.server.handler.ResourceHandler">
        &lt;Set name="directoriesListed">true&lt;/Set>
+
        <Set name="directoriesListed">true</Set>
&lt;Set name="welcomeFiles">
+
<Set name="welcomeFiles">
  &lt;Array type="String">&lt;Item>index.html&lt;/Item>&lt;/Array>
+
  <Array type="String"><Item>index.html</Item></Array>
&lt;/Set>
+
</Set>
        &lt;Set name="resourceBase">.</Set>
+
        <Set name="resourceBase">.</Set>
      &lt;/New>
+
      </New>
    &lt;/Item>
+
    </Item>
    &lt;Item>
+
    <Item>
      &lt;New class="org.eclipse.jetty.server.handler.DefaultHandler">
+
      <New class="org.eclipse.jetty.server.handler.DefaultHandler">
      &lt;/New>
+
      </New>
    &lt;/Item>
+
    </Item>
  &lt;/Array>
+
  </Array>
         &lt;/Set>
+
         </Set>
       &lt;/New>
+
       </New>
     &lt;/Set>
+
     </Set>
&lt;/Configure>
+
</Configure>
  
</pre>
+
</source>
  
  
Line 212: Line 211:
  
 
The following code is based on [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/OneContext.html OneContext.java] and sets context path and classloader for the hello handler:
 
The following code is based on [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/OneContext.html OneContext.java] and sets context path and classloader for the hello handler:
<pre>
+
<source lang="java">
 
public class OneContext
 
public class OneContext
 
{
 
{
Line 231: Line 230:
 
     }
 
     }
 
}
 
}
</pre>
+
</source>
  
 
== Servlets ==  
 
== 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 [http://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk/example-jetty-embedded/src/main/java/org/eclipse/jetty/embedded/HelloServlet.java HelloServlet.java]:
 
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 [http://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk/example-jetty-embedded/src/main/java/org/eclipse/jetty/embedded/HelloServlet.java HelloServlet.java]:
<pre>public class HelloServlet extends HttpServlet
+
<source lang="java">public class HelloServlet extends HttpServlet
 
{
 
{
 
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
 
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
Line 246: Line 245:
 
     }
 
     }
 
}
 
}
</pre>
+
</source>
  
 
== ServletContext ==
 
== ServletContext ==
 
A [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/servlet/ServletContextHandler.html ServletContextHandler] is a specialization of ContextHandler with support for standard servlets.  The following code from [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/OneServletContext.html OneServletContext] shows 3 instances of the helloworld servlet registered with a ServletContextHandler:
 
A [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/servlet/ServletContextHandler.html ServletContextHandler] is a specialization of ContextHandler with support for standard servlets.  The following code from [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/OneServletContext.html OneServletContext] shows 3 instances of the helloworld servlet registered with a ServletContextHandler:
<pre>
+
<source lang="java">
 
public class OneServletContext
 
public class OneServletContext
 
{
 
{
Line 269: Line 268:
 
     }
 
     }
 
}
 
}
</pre>
+
</source>
  
 
== Web Application Context ==
 
== Web Application Context ==
  
 
A [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/webapp/WebAppContext.html Web Applications context] is a specialization of ServletContextHandler that uses the standard layout and web.xml to configure the servlets, filters and other features:
 
A [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/webapp/WebAppContext.html Web Applications context] is a specialization of ServletContextHandler that uses the standard layout and web.xml to configure the servlets, filters and other features:
<pre>
+
<source lang="java">
  
 
public class OneWebApp
 
public class OneWebApp
Line 293: Line 292:
 
     }
 
     }
 
}
 
}
</pre>
+
</source>
  
 
== Context Handler Collection ==  
 
== Context Handler Collection ==  
A [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/ContextHandlerCollection.html 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:
+
A [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/ContextHandlerCollection.html 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:
<pre>
+
<source lang="java">
 
public class ManyContexts
 
public class ManyContexts
 
{
 
{
Line 324: Line 323:
 
     }
 
     }
 
}
 
}
</pre>
+
</source>
  
 
}}
 
}}

Revision as of 07:19, 31 July 2009



Contents

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).

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 FileServer example could 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>


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();
    }
}