| 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 =

−

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.

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.

+

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]. Put another way, running Jetty in embedded mode means putting an HTTP module into your application, rather than putting your application into an HTTP server.

+

+

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.

+

+

Before doing this tutorial, it is worth while to do the [[Jetty/Tutorial/Jetty HelloWorld|Hello World]] tutorial. This tutorial is also available as a [http://vimeo.com/19146453 Embedding Jetty Webinar recording].

+

+

{{Note|Jetty Version|The code in this tutorial is from Jetty 7, but should also work on Jetty 8. For the latest stable code, follow the links to the code xref from the latest release, which might vary slightly from the code examples given on this page.}}

| details =

| details =

Line 12:

Line 18:

# Add/Configure Handlers

# Add/Configure Handlers

# Add/Configure Servlets/Webapps to Handlers

# Add/Configure Servlets/Webapps to Handlers

−

# start the server

+

# Start the server

−

# wait (join the server to prevent main exiting).

+

# Wait (join the server to prevent main exiting)

−

== Servers ==

+

== Creating a 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:

+

The following code from [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/SimplestServer.html SimplestServer.java] instantiates and runs the simplest possible Jetty server:

−

<pre>

+

<source lang="java">

public class SimplestServer

public class SimplestServer

{

{

Line 27:

Line 33:

}

}

}

}

−

</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 an HTTP server on port 8080. It is not a very useful server as it has no handlers and thus returns a 404 error for every request.

−

== Handlers ==

+

== Writing 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:

+

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:

* 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://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/HelloHandler.html HelloHandler.java] shows a simple hello world handler:

* request - The immutable request object, which may have been wrapped.

+

* request–the immutable request object, which might have been wrapped.

−

* response - The response that may have been wrapped.

+

* response–the response, which might 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 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 [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 a Jetty server can use this handler:

−

<pre>

+

<source lang="java">

public static void main(String[] args) throws Exception

public static void main(String[] args) throws Exception

{

{

Line 73:

Line 78:

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 an HTTP server based on Jetty. However, complex request handling is typically built from multiple Handlers. We will look in later sections at how you can combine handlers like aspects. You can see some of the handlers available in Jetty in the [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/package-frame.html org.eclipse.jetty.server.handler] package.

−

== Connectors ==

+

== Configuring Connectors ==

−

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.

+

To configure the HTTP connectors that the server uses, you can set one or more [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/Connector.html connector]s on the server. You can configure each connector 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 to set and configure connectors for the Hello World example:

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 calls 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 used 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.

−

== File Server ==

+

See also [[Jetty/Howto/Write_Jetty_Handler|How to Write a Jetty Handler]].

+

+

==Configuring a File Server ==

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

{

{

public static void main(String[] args) throws Exception

public static void main(String[] args) throws Exception

{

{

−

Server server = new Server(8080);

+

Server server = new Server();

+

SelectChannelConnector connector = new SelectChannelConnector();

+

connector.setPort(8080);

+

server.addConnector(connector);

ResourceHandler resource_handler = new ResourceHandler();

ResourceHandler resource_handler = new ResourceHandler();

Line 150:

Line 161:

}

}

}

}

−

</pre>

+

</source>

+

+

The resource handler is passed the request first and looks for a matching file in the local directory to serve. If it does not find a file, the request passes to the default handler which generates a 404 (or favicon.ico).

+

+

=== Configuring a File Server with XML ===

+

Now is a good time to remind you that the [[Jetty/Reference/jetty.xml syntax|Jetty XML]] configuration format can render simple Java code into XML configuration. So the File Server example above can be written with a little reordering in Jetty XML as follows:

You can run this XML file from the [http://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk/example-jetty-embedded/src/main/java/org/eclipse/jetty/embedded/FileServerXml.java FileServerXml.java] class:

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

+

See also [[Jetty/Howto/Spring|How to Configure Jetty with Spring]].

−

== Contexts ==

+

== Setting Contexts ==

−

A [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/ContextHandler.html ContextHandler] is a HandlerWrapper that will respond only to requests that have a URI prefix that match the configured context path.

+

A [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/ContextHandler.html ContextHandler] is a HandlerWrapper that responds only to requests that have a URI prefix that matches 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:

+

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

* A Thread Context classloader.

* A Thread Context classloader.

* A set of attributes

* A set of attributes

−

* A set init parameters

+

* A set of init parameters

* A resource base (aka document root)

* A resource base (aka document root)

* A set of virtual host names

* A set of virtual host names

Line 167:

Line 273:

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 186:

Line 292:

}

}

}

}

−

</pre>

+

</source>

−

== Servlets ==

+

== Creating 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]:

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 three instances of the helloworld servlet registered with a ServletContextHandler:

A [http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/webapp/WebAppContext.html Web Applications context] is a variation of ServletContextHandler that uses the standard layout and web.xml to configure the servlets, filters and other features:

+

<source lang="java">

+

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

+

}

+

}

+

</source>

+

+

If during development, you have not assembled your application into a WAR file, you can run it from its source components with something like:

+

+

<source lang="java">

+

+

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

+

}

+

}

+

</source>

+

+

== Configuring a 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:

Embedding JSP support can be a bit confusing if you look at the Jars under the lib/jsp directory in the jetty distribution. This is because we have to ship from Eclipse with the JSP bundles that are marked up as OSGi bundles, which you cannot directly download from Maven Central. There are dependencies available in Maven Central that work because they were the actual source for the OSGi bundles themselves. The OSGi bundles are simply these Maven Central artifacts decomposed into a few extra bundles.

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. Put another way, running Jetty in embedded mode means putting an HTTP module into your application, rather than putting your application into an HTTP server.

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.

Jetty VersionThe code in this tutorial is from Jetty 7, but should also work on Jetty 8. For the latest stable code, follow the links to the code xref from the latest release, which might vary slightly from the code examples given on this page.

Details

To embed a Jetty server, the following steps are typical:

Create the server

Add/Configure Connectors

Add/Configure Handlers

Add/Configure Servlets/Webapps to Handlers

Start the server

Wait (join the server to prevent main exiting)

Creating a Server

The following code from SimplestServer.java instantiates and runs the simplest possible Jetty server:

You now know everything you need to know to write an HTTP server based on Jetty. However, complex request handling is typically built from multiple Handlers. We will look in later sections at how you can combine handlers like aspects. You can see some of the handlers available in Jetty in the org.eclipse.jetty.server.handler package.

Configuring Connectors

To configure the HTTP connectors that the server uses, you can set one or more connectors on the server. You can configure each connector with details such as interface, port, buffer sizes, timeouts, etc.

The following code is based on ManyConnectors.java and shows how to set and configure connectors for the Hello World example:

Understanding 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 calls 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 used 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.

The resource handler is passed the request first and looks for a matching file in the local directory to serve. If it does not find a file, the request passes to the default handler which generates a 404 (or favicon.ico).

Configuring a File Server with XML

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

Creating 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:

Setting a ServletContext

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

Configuring a 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:

Embedding JSP

Embedding JSP support can be a bit confusing if you look at the Jars under the lib/jsp directory in the jetty distribution. This is because we have to ship from Eclipse with the JSP bundles that are marked up as OSGi bundles, which you cannot directly download from Maven Central. There are dependencies available in Maven Central that work because they were the actual source for the OSGi bundles themselves. The OSGi bundles are simply these Maven Central artifacts decomposed into a few extra bundles.