Skip to main content
Quickstart Guide

Introducing Jetty

What is Jetty?

Jetty is an open-source project providing an HTTP server, HTTP client, and javax.servlet container.

This guide is broken up in to five parts:

  • The first section emphasizes beginning to use Jetty. It provides information about what Jetty is and where you can download it, and where to find Jetty in repositories like Central Maven. It also provides a Quick Start guide on how to get Jetty up and running as well as an overview of how and what to configure in Jetty.

  • The second section of the guide deals with configuring Jetty at a more granular level. It explains how to use Jetty to deploy web applications, configure contexts and connects, and how to implement SSL and other security measures.

  • Administration of Jetty is the focus of the third section of the guide. From server startup to session management, logging, HTTP/2 support and Jetty optimization, these chapters will help administrators get the most out of their Jetty server instances. This section also covers configuring many of the most common servlet container features such as JNDI and JMX.

  • Aimed at advanced users of Jetty, the fourth section of the guide focuses on Jetty development. A large portion of this section is focused on using Jetty as an embedded server in existing applications. It contains several examples and how-to guides for making the most out of the Jetty framework. This section also includes a guide on using the Jetty Maven plugin as well as information on debugging Jetty.

  • The final section of the guide is a reference section. Included there are guides on Jetty architecture and Jetty XML syntax, alternate distributions of Jetty and even troubleshooting of common issues. There is also a chapter on getting involved in the Jetty community including information on how to contribute code and how to find help.

Feedback is always welcome! Additionally, if you are interested in how to contribute to the open source project there is a section on that as well!

What Version Do I Use?

Jetty 9 is the most recent version of Jetty and has a great many improvements over previous versions. This documentation which focuses on Jetty 9. While many people continue to use older versions of Jetty, we generally recommend using Jetty 9 as it represents the version of Jetty that we will actively maintain and improve over the next few years.

It is important that only stable releases are used in production environments. Versions that have been deprecated or are released as Milestones (M) or Release Candidates (RC) are not suitable for production as they may contain security flaws or incomplete/non-functioning feature sets.
Table 1. Jetty Versions
Version Year Home Min JVM Protocols Servlet JSP Status

10

2019-

Eclipse

11 (1)

HTTP/1.1 (RFC 7230), HTTP/2 (RFC 7540), WebSocket (RFC 6455, JSR 356), FastCGI

4.0.2

2.3

UNSTABLE / Alpha

9.4

2016-

Eclipse

1.8

HTTP/1.1 (RFC 7230), HTTP/2 (RFC 7540), WebSocket (RFC 6455, JSR 356), FastCGI

3.1

2.3

Stable

9.3

2015-

Eclipse

1.8 (2)

HTTP/1.1 (RFC 7230), HTTP/2 (RFC 7540), WebSocket (RFC 6455, JSR 356), FastCGI

3.1

2.3

Deprecated

9.2

2014-2018

Eclipse

1.7 (2)

HTTP/1.1 RFC2616, javax.websocket, SPDY v3

3.1

2.3

Deprecated / End of Life January 2018

9.1

2013-2014

Eclipse

1.7 (2)

HTTP/1.1 RFC2616

3.1

2.3

Deprecated / End of Life May 2014

9.0

2013-2013

Eclipse

1.7 (2)

HTTP/1.1 RFC2616

3.1-beta

2.3

Deprecated / End of Life November 2013

8

2009-2014

Eclipse/Codehaus

1.6 (2)

HTTP/1.1 RFC2616, WebSocket RFC 6455, SPDY v3

3.0

2.2

Deprecated / End of Life November 2014

7

2008-2014

Eclipse/Codehaus

1.5

HTTP/1.1 RFC2616, WebSocket RFC 6455, SPDY v3

2.5

2.1

Deprecated / End of Life November 2014

6

2006-2010

Codehaus

1.4-1.5

HTTP/1.1 RFC2616

2.5

2.0

Deprecated / End of Life November 2010

5

2003-2009

Sourceforge

1.2-1.5

HTTP/1.1 RFC2616

2.4

2.0

Antique

4

2001-2006

Sourceforge

1.2, J2ME

HTTP/1.1 RFC2616

2.3

1.2

Ancient

3

1999-2002

Sourceforge

1.2

HTTP/1.1 RFC2068

2.2

1.1

Fossilized

2

1998-2000

Mortbay

1.1

HTTP/1.0 RFC1945

2.1

1.0

Legendary

1

1995-1998

Mortbay

1.0

HTTP/1.0 RFC1945

-

-

Mythical

  1. JPMS module support is optional

  2. JDK9 and newer is not supported if using MultiRelease JAR Files, or Bytecode / Annotation scanning.

Jetty and Java EE Web Profile

Jetty implements aspects of the Java EE specification, primarily the Servlet Specification. Recent releases of the Java EE platform have introduced a Web Profile, recognizing that many developers need only a subset of the many technologies under the Java EE umbrella.

While Jetty itself does not ship all of the Web Profile technologies, Jetty architecture is such that you can plug in third party implementations to produce a container customized to your exact needs.

Java EE 7 Web Profile

In the forthcoming Java EE-7 specification, the Web Profile reflects updates in its component specifications and adds some new ones:

Table 2. JavaEE7 Web Profile
JSR Name Included with jetty-9.1.x Pluggable

JSR 340

Servlet Specification API 3.1

Yes

JSR 344

Java Server Faces 2.2 (JSF)

No

Yes, Mojarra or MyFaces

JSR 245 / JSR 341

Java Server Pages 2.3/Java Expression Language 3.0 (JSP/EL)

Yes

Yes

JSR 52

Java Standard Tag Library 1.2 (JSTL)

Yes

Yes

JSR 45

Debugging Support for Other Languages 1.0

Yes (via JSP)

Yes (via JSP)

JSR 346

Contexts and Dependency Injection for the JavaEE Platform 1.1 (Web Beans)

No

Yes, Weld

JSR 330

Dependency Injection for Java 1.0

No

Yes as part of a CDI implementation, Weld

JSR 316

Managed Beans 1.0

No

Yes, as part of another technology

JSR 345

Enterprise JavaBeans 3.2 Lite

No

JSR 338

Java Persistence 2.1 (JPA)

No

Yes, eg Hibernate

JSR 250

Common Annotations for the Java Platform 1.2

Yes

Partially (for non-core Servlet Spec annotations)

JSR 907

Java Transaction API 1.2 (JTA)

Yes

Yes

JSR 349

Bean Validation 1.1

No

Yes as part of another technology eg JSF, or a stand-alone implementation such as Hiberate Validator

JSR 339

Java API for RESTful Web Services 2.0 (JAX-RS)

No

JSR 356

Java API for Websocket 1.0

Yes

No

JSR 353

Java API for JSON Processing 1.0 (JSON-P)

No

Yes, eg JSON-P reference implementation

JSR 318

Interceptors 1.2

No

Yes as part of a CDI implementation

Jetty EE 6 Web Profile

Here is the matrix of JSRs for Java EE 6 Web Profile, and how they relate to Jetty:

Table 3. Java EE 6 Web Profile
JSR Name Included with jetty-9.0.x Pluggable

JSR 315

Servlet Specification API 3.0

Yes

JSR 314

JavaServer Faces 2.0 (JSF)

No

Yes, for example, Mojarra or MyFaces

JSR 245

JavaServer Pages 2.2/Java Expression Language 2.2 (JSP/EL)

Yes

Yes

JSR 52

Java Standard Tag Library 1.2 (JSTL)

Yes

Yes

JSR 45

Debugging Support for Other Languages 1.0

Yes (via JSP)

Yes (via JSP)

JSR 299

Contexts and Dependency Injection for the Java EE Platform 1.0 (Web Beans)

No

Yes, Weld or OpenWebBeans

JSR 330

Dependency Injection for Java 1.0

No

Yes as part of a CDI implementation, Weld

JSR 316

Managed Beans 1.0

No

Yes, as part of another technology.

JSR 318

Enterprise JavaBeans 3.1

No

Yes, OpenEJB

JSR 317

Java Persistence 2.0 (JPA)

No

Yes, Hibernate

JSR 250

Common Annotations for the Java Platform

Yes

Partially (for non-core Servlet Spec annotations)

JSR 907

Java Transaction API (JTA)

Yes

Implementations are pluggable, such as Atomikos, JOTM, Jencks (Geronimo Transaction Manager)

JSR 303

Bean Validation 1.0

No

Yes as part of another technology (JSF), or a stand-alone implementation such as Hiberate Validator

Finding Jetty in Maven

It is important that only stable releases are used in production environments. Versions that have been deprecated or are released as Milestones (M) or Release Candidates (RC) are not suitable for production as they may contain security flaws or incomplete/non-functioning feature sets.

Maven Coordinates

Jetty has existed in Maven Central almost since its inception, though the coordinates have changed over the years. When Jetty was based at SourceForge and then The Codehaus it was located under the groupId of org.mortbay.jetty. With Jetty 7 the project moved to the Eclipse foundation and to a new groupId at that time to reflect its new home.

The top level Project Object Model (POM) for the Jetty project is located under the following coordinates.

<dependency>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>jetty-project</artifactId>
  <version>${project.version}</version>
</dependency>

Changelogs in Maven Central

The changes between versions of Jetty are tracked in a file called VERSIONS.txt, which is under source control and is generated on release. Those generated files are also uploaded into Maven Central during the release of the top level POM. You can find them as a classifier marked artifact.

<dependency>
  <groupId>org.eclipse.jetty</groupId>
  <artifactId>jetty-project</artifactId>
  <version>${project.version}</version>
  <classifier>version</classifier>
  <type>txt</type>
</dependency>

Using Jetty

You can use Jetty in many different ways ranging from embedding Jetty in applications, launching it from different build systems, from different JVM-based languages, or as a standalone distribution. This guide covers the latter, a standalone distribution suitable for deploying web applications.

Downloading Jetty

Downloading the Jetty Distribution

The standalone Jetty distribution is available for download from the Eclipse Foundation:

It is available in both zip and gzip formats; download the one most appropriate for your system. When you download and unpack the binary, it is extracted into a directory called jetty-distribution-VERSION. Put this directory in a convenient location. The rest of the instructions in this documentation refer to this location as either $JETTY_HOME or as $(jetty.home).

It is important that only stable releases are used in production environments. Versions that have been deprecated or are released as Milestones (M) or Release Candidates (RC) are not suitable for production as they may contain security flaws or incomplete/non-functioning feature sets.
Distribution Content

A summary of the distribution’s contents follows. The top-level directory contains:

Table 4. Contents
Location Description

license-eplv10-aslv20.html

License file for Jetty

README.txt

Useful getting started information

VERSION.txt

Release information

bin/

Utility shell scripts to help run Jetty on Unix systems

demo-base/

A Jetty base directory to run a Jetty server with demonstration webapps

etc/

Directory for Jetty XML configuration files

lib/

All the JAR files necessary to run Jetty

logs/

Directory for request logs

modules/

Directory of module definitions

notice.html

License information and exceptions

resources/

Directory containing additional resources for classpath, activated via configuration

start.ini

File containing the arguments that are added to the effective command line (modules, properties and XML configuration files)

start.jar

Jar that invokes Jetty (see also Running Jetty)

webapps/

Directory containing webapps that run under the default configuration of Jetty

Downloading the Jetty-Home Distribution

Jetty-Home is an alternate version of the distribution that contains only the necessary items to host a Jetty distribution. It is intended for advanced users who are already familiar with Jetty and want to download a smaller distribution package. Jetty-Home can be downloaded from the Maven Central repository:

Like the main Jetty distribution, Jetty-Home is available in both zip and gzip formats; download the one most appropriate for your system. Notice that there are a number of other files with extensions of .sha or .md5 which are checksum files. When you download and unpack the binary, it is extracted into a directory called jetty-home-VERSION. Put this directory in a convenient location.

Distribution Content

A summary of the Jetty-Home’s distribution contents follows. The top-level directory contains:

Table 5. Contents
Location Description

license-eplv10-aslv20.html

License file for Jetty

VERSION.txt

Release information

etc/

Directory for Jetty XML configuration files

lib/

All the JAR files necessary to run Jetty

modules/

Directory of module definitions

notice.html

License information and exceptions

start.jar

Jar that invokes Jetty (see also Running Jetty)

Running Jetty

Once you have a copy of the Jetty distribution downloaded, extract the zip or tar.gz file to a location where you have read and write access. Jetty has no GUI (Graphical User Interface), so running the server and performing many configuration options is done from the command line.

Once you have access to your system’s command line, navigate to the directory where you unpacked your copy of the Jetty distribution. To start Jetty on the default port of 8080, run the following command:

$ java -jar start.jar
2017-09-20 15:45:11.986:INFO::main: Logging initialized @683ms to org.eclipse.jetty.util.log.StdErrLog
2017-09-20 15:45:12.197:WARN:oejs.HomeBaseWarning:main: This instance of Jetty is not running from a separate {jetty.base} directory, this is not recommended.  See documentation at http://www.eclipse.org/jetty/documentation/current/startup.html
2017-09-20 15:45:12.243:INFO:oejs.Server:main: 10.0.0.alpha2
2017-09-20 15:45:12.266:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:///installs/repository/jetty/webapps/] at interval 1
2017-09-20 15:45:12.298:INFO:oejs.AbstractConnector:main: Started ServerConnector@39c0f4a{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2017-09-20 15:45:12.298:INFO:oejs.Server:main: Started @995ms

You can point a browser at this server at http://localhost:8080. However, as there are no webapps deployed in the $JETTY_HOME directory, you will see a 404 error page served by Jetty. To stop the server, press CTRL + c or CTRL + z in your terminal.

Note the HomeBaseWarning - it is not recommended to run Jetty from the $JETTY_HOME directory. Instead, see how to create a Jetty Base below.

You will see examples throughout the documentation referencing $JETTY_HOME and $JETTY_BASE as well as {jetty.home} and {jetty.base}. These terms are used to refer to the location of your Jetty installation directories. Many users find it helpful to define $JETTY_HOME as an environment variable that maps to their Jetty distribution directory. More information can be found in our Administration section on managing Jetty Home and Jetty Base.

Demo Base

Within the standard Jetty distribution there is the demo-base directory. This is a fully-functioning Jetty Base (more on that later) complete with numerous web applications demonstrating different Jetty functionality. Additionally, the demo-base demonstrates the recommended way to run a Jetty base in a directory separate from $JETTY_HOME:

$ cd demo-base/
$ java -jar ../start.jar
2017-09-20 16:23:03.563:INFO::main: Logging initialized @429ms to org.eclipse.jetty.util.log.StdErrLog
2017-09-20 16:23:03.802:WARN::main: demo test-realm is deployed. DO NOT USE IN PRODUCTION!
2017-09-20 16:23:03.804:INFO:oejs.Server:main: 10.0.0.alpha2
2017-09-20 16:23:03.819:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:///installs/repository/jetty/demo-base/webapps/] at interval 1
2017-09-20 16:23:04.098:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=102ms
2017-09-20 16:23:04.103:WARN::main: async-rest webapp is deployed. DO NOT USE IN PRODUCTION!
2017-09-20 16:23:04.267:INFO:oejs.session:main: DefaultSessionIdManager workerName=node0
2017-09-20 16:23:04.267:INFO:oejs.session:main: No SessionScavenger set, using defaults
2017-09-20 16:23:04.268:INFO:oejs.session:main: Scavenging every 660000ms
2017-09-20 16:23:04.306:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@371a67ec{/async-rest,[file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-async-rest.war-_async-rest-any-5319296087878801290.dir/webapp/, jar:file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-async-rest.war-_async-rest-any-5319296087878801290.dir/webapp/WEB-INF/lib/example-async-rest-jar-10.0.0.alpha2.jar!/META-INF/resources],AVAILABLE}{/async-rest.war}
2017-09-20 16:23:04.429:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=53ms
2017-09-20 16:23:04.432:WARN::main: test webapp is deployed. DO NOT USE IN PRODUCTION!
2017-09-20 16:23:04.511:INFO:oejsh.ManagedAttributeListener:main: update PushFilter null->org.eclipse.jetty.servlets.PushCacheFilter@2362f559 on o.e.j.w.WebAppContext@35e2d654{/test,file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test.war-_test-any-6279588879522983394.dir/webapp/,STARTING}{/test.war}
2017-09-20 16:23:04.516:INFO:oejsh.ManagedAttributeListener:main: update QoSFilter null->org.eclipse.jetty.servlets.QoSFilter@7770f470 on o.e.j.w.WebAppContext@35e2d654{/test,file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test.war-_test-any-6279588879522983394.dir/webapp/,STARTING}{/test.war}
2017-09-20 16:23:04.519:WARN:oeju.DeprecationWarning:main: Using @Deprecated Class org.eclipse.jetty.servlets.MultiPartFilter
2017-09-20 16:23:04.549:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@35e2d654{/test,file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test.war-_test-any-6279588879522983394.dir/webapp/,AVAILABLE}{/test.war}
2017-09-20 16:23:04.646:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=12ms
2017-09-20 16:23:04.649:WARN::main: test-jndi webapp is deployed. DO NOT USE IN PRODUCTION!
2017-09-20 16:23:04.697:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@561b6512{/test-jndi,file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test-jndi.war-_test-jndi-any-6023636263414992288.dir/webapp/,AVAILABLE}{/test-jndi.war}
2017-09-20 16:23:04.770:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=40ms
2017-09-20 16:23:05.036:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@2beee7ff{/proxy,file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-javadoc-proxy.war-_javadoc-proxy-any-2758874759195597975.dir/webapp/,AVAILABLE}{/javadoc-proxy.war}
2017-09-20 16:23:05.072:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=16ms
2017-09-20 16:23:05.074:WARN::main: test-jaas webapp is deployed. DO NOT USE IN PRODUCTION!
2017-09-20 16:23:05.098:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@506ae4d4{/test-jaas,file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test-jaas.war-_test-jaas-any-8067423971450448377.dir/webapp/,AVAILABLE}{/test-jaas.war}
2017-09-20 16:23:05.182:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=37ms
2017-09-20 16:23:05.184:WARN::main: test-spec webapp is deployed. DO NOT USE IN PRODUCTION!
2017-09-20 16:23:05.243:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@45099dd3{/test-spec,[file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test-spec.war-_test-spec-any-1205866915335004234.dir/webapp/, jar:file:///private/var/folders/h6/yb_lbnnn11g0y1jjlvqg631h0000gn/T/jetty-0.0.0.0-8080-test-spec.war-_test-spec-any-1205866915335004234.dir/webapp/WEB-INF/lib/test-web-fragment-10.0.0.alpha2.jar!/META-INF/resources],AVAILABLE}{/test-spec.war}
2017-09-20 16:23:05.247:INFO:oejsh.ContextHandler:main: Started o.e.j.s.h.MovedContextHandler@3e08ff24{/oldContextPath,null,AVAILABLE}
2017-09-20 16:23:05.274:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=18ms
2017-09-20 16:23:05.296:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@5ddeb7cb{/,file:///installs/repository/jetty/demo-base/webapps/ROOT/,AVAILABLE}{/ROOT}
2017-09-20 16:23:05.326:INFO:oeja.AnnotationConfiguration:main: Scanning elapsed time=21ms
2017-09-20 16:23:05.352:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@6b695b06{/doc,file:///installs/repository/jetty/demo-base/webapps/doc/,AVAILABLE}{/doc}
2017-09-20 16:23:05.370:INFO:oejs.AbstractConnector:main: Started ServerConnector@28cda624{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2017-09-20 16:23:05.380:INFO:oejus.SslContextFactory:main: x509=X509@126253fd(jetty,h=[jetty.eclipse.org],w=[]) for SslContextFactory@57db2b13(file:///installs/repository/jetty/demo-base/etc/keystore,file:///installs/repository/jetty/demo-base/etc/keystore)
2017-09-20 16:23:05.381:INFO:oejus.SslContextFactory:main: x509=X509@475c9c31(mykey,h=[],w=[]) for SslContextFactory@57db2b13(file:///installs/repository/jetty/demo-base/etc/keystore,ffile:///installs/repository/jetty/demo-base/etc/keystore)
2017-09-20 16:23:05.523:INFO:oejs.AbstractConnector:main: Started ServerConnector@53f3bdbd{SSL,[ssl, http/1.1]}{0.0.0.0:8443}
2017-09-20 16:23:05.524:INFO:oejs.Server:main: Started @2390ms

You can visit this demo server by pointing a browser at http://localhost:8080, which will now show a welcome page and several demo/test web applications.

The demonstration web applications are not necessarily secure and should not be deployed in production web servers.

You can see the configuration of the demo-base by using the following commands:

> cd $JETTY_HOME/demo-base/
> java -jar $JETTY_HOME/start.jar --list-modules
...

> java -jar $JETTY_HOME/start.jar --list-config
...

The --list-modules command will return a complete list of available and enabled modules for the server. It will also display the location of the modules, how and in what order they are implemented, dependent modules, and associated jar files.

The --list-config command displays a trove of information about the server including the Java and Jetty environments, the configuration order, any JVM arguments or System Properties set, general server properties, a full listing of the Jetty server class path, and active Jetty XML files.

Common Jetty Configuration

Creating a new Jetty Base

The demo-base directory described earlier is an example of the jetty.base mechanism. A Jetty base directory allows the configuration and web applications of a server instance to be stored separately from the Jetty distribution, so that upgrades can be done with minimal disruption. Jetty’s default configuration is based on two properties:

jetty.home

The property that defines the location of the Jetty distribution, its libs, default modules and default XML files (typically start.jar, lib, etc).

jetty.base

The property that defines the location of a specific implementation of a Jetty server, its configuration, logs and web applications (typically start.d/*.ini files, logs and webapps).

Your Jetty Home directory should be treated as a standard of truth and remain unmodified or changed. Changes or additions to your configuration should take place in the Jetty Base directory.

The jetty.home and jetty.base properties may be explicitly set on the command line, or they can be inferred from the environment if used with commands like:

> cd $JETTY_BASE
> java -jar $JETTY_HOME/start.jar

The following commands create a new base directory, enables both the HTTP connector and the web application deployer modules, and copies a demo webapp to be deployed:

> JETTY_BASE=/tmp/mybase
> mkdir $JETTY_BASE
> cd $JETTY_BASE
> java -jar $JETTY_HOME/start.jar

WARNING: Nothing to start, exiting ...

Usage: java -jar start.jar [options] [properties] [configs]
       java -jar start.jar --help  # for more information

> java -jar $JETTY_HOME/start.jar --create-startd
INFO : Base directory was modified
> java -jar $JETTY_HOME/start.jar --add-to-start=http,deploy

INFO: server          initialised (transitively) in ${jetty.base}/start.d/server.ini
INFO: http            initialised in ${jetty.base}/start.d/http.ini
INFO: security        initialised (transitively) in ${jetty.base}/start.d/security.ini
INFO: servlet         initialised (transitively) in ${jetty.base}/start.d/servlet.ini
INFO: webapp          initialised (transitively) in ${jetty.base}/start.d/webapp.ini
INFO: deploy          initialised in ${jetty.base}/start.d/deploy.ini
MKDIR: ${jetty.base}/webapps
INFO: Base directory was modified

> cp $JETTY_HOME/demo-base/webapps/async-rest.war webapps/ROOT.war
> java -jar $JETTY_HOME/start.jar

2015-06-04 11:10:16.286:INFO::main: Logging initialized @274ms
2015-06-04 11:10:16.440:INFO:oejs.Server:main: jetty-9.3.0.v20150601
2015-06-04 11:10:16.460:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:///tmp/mybase/webapps/] at interval 1
2015-06-04 11:10:16.581:WARN::main: async-rest webapp is deployed. DO NOT USE IN PRODUCTION!
2015-06-04 11:10:16.589:INFO:oejw.StandardDescriptorProcessor:main: NO JSP Support for /, did not find org.eclipse.jetty.jsp.JettyJspServlet
2015-06-04 11:10:16.628:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@1a407d53{/,[file:///tmp/jetty-0.0.0.0-8080-ROOT.war-_-any-4510228025526425427.dir/webapp/, jar:file:///tmp/jetty-0.0.0.0-8080-ROOT.war-_-any-4510228025526425427.dir/webapp/WEB-INF/lib/example-async-rest-jar-10.0.0.alpha2.jar!/META-INF/resources],AVAILABLE}{/ROOT.war}
2015-06-04 11:10:16.645:INFO:oejs.ServerConnector:main: Started ServerConnector@3abbfa04{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
2015-06-04 11:10:16.646:INFO:oejs.Server:main: Started @634ms

Changing the Jetty Port

You can configure Jetty to run on a different port by setting the jetty.http.port property on the command line:

> cd $JETTY_BASE
> java -jar $JETTY_HOME/start.jar jetty.http.port=8081
...

When the server starts, it will now run on port 8081. It is important to note that setting properties on the command line will only take affect for that instance of the server. To change the configuration so that the server will always start on the desired port, you will need to edit the start.d/http.ini

The configuration by properties works via the following chain:

  • The start.d/http.ini file is part of the effective command line and contains the --module=http argument which activates the http module.

  • The modules/http.mod file defines the http module which specifies the etc/jetty-http.xml configuration file and the template ini properties it uses.

  • The jetty.http.port property is used by the Property XML element in etc/jetty.http.xml to inject the ServerConnector instance with the port.

For more information see the Quickstart Configuration Guide and Configuring Connectors.

Adding SSL for HTTPS & HTTP2

Building on the example above, we can activate additional modules to add support HTTPS and HTTP2 for the server. To add HTTPS and HTTP2 connectors to a Jetty configuration, the modules can be activated by the following command:

> java -jar $JETTY_HOME/start.jar --add-to-start=https,http2

ALERT: There are enabled module(s) with licenses.
The following 1 module(s):
 + contains software not provided by the Eclipse Foundation!
 + contains software not covered by the Eclipse Public License!
 + has not been audited for compliance with its license

 Module: alpn-impl/alpn-8
  + ALPN is a hosted at github under the GPL v2 with ClassPath Exception.
  + ALPN replaces/modifies OpenJDK classes in the sun.security.ssl package.
  + http://github.com/jetty-project/jetty-alpn
  + http://openjdk.java.net/legal/gplv2+ce.html

Proceed (y/N)? y
INFO  : alpn-impl/alpn-1.8.0_92 dynamic dependency of alpn-impl/alpn-8
INFO  : alpn            transitively enabled, ini template available with --add-to-start=alpn
INFO  : alpn-impl/alpn-8 dynamic dependency of alpn
INFO  : http2           initialized in ${jetty.base}/start.d/http2.ini
INFO  : https           initialized in ${jetty.base}/start.d/https.ini
INFO  : ssl             transitively enabled, ini template available with --add-to-start=ssl
MKDIR : ${jetty.base}/lib/alpn
DOWNLD: https://repo1.maven.org/maven2/org/mortbay/jetty/alpn/alpn-boot/8.1.8.v20160420/alpn-boot-8.1.8.v20160420.jar to ${jetty.base}/lib/alpn/alpn-boot-8.1.8.v20160420.jar
MKDIR : ${jetty.base}/etc
COPY  : ${jetty.home}/modules/ssl/keystore to ${jetty.base}/etc/keystore
INFO  : Base directory was modified

> java -jar $JETTY_HOME/start.jar
[...]
2017-05-22 12:48:23.271:INFO:oejs.AbstractConnector:main: Started ServerConnector@134d0064{SSL,[ssl, alpn, h2, http/1.1]}{0.0.0.0:8443}
[...]

The --add-to-start command sets up the effective command line in the ini files to run an ssl connection that supports the HTTPS and HTTP2 protocols as follows:

  • transitively enabled the ssl module that configures an SSL connector (eg port, keystore etc.) by adding etc/jetty-ssl.xml and etc/jetty-ssl-context.xml to the effective command line.

  • transitively enabled the alpn module that configures protocol negotiation on the SSL connector by adding etc/jetty-alpn.xml to the effective command line.

  • creates start.d/https.ini that configures the HTTPS protocol on the SSL connector by adding etc/jetty-https.xml to the effective command line.

  • creates start.d/http2.ini that configures the HTTP/2 protocol on the SSL connector by adding etc/jetty-http2.xml to the effective command line.

  • checks for the existence of a etc/keystore file and if not present, downloads a demonstration keystore file.

Changing the Jetty HTTPS Port

You can configure the SSL connector to run on a different port by setting the jetty.ssl.port property on the command line:

> cd $JETTY_BASE
> java -jar $JETTY_HOME/start.jar jetty.ssl.port=8444

Alternatively, property values can be added to the effective command line built from the start.ini file or start.d/*.ini files, depending on your set up. Please see the section on Start.ini vs. Start.d for more information.

More start.jar Options

The job of the start.jar is to interpret the command line, start.ini and start.d directory (and associated .ini files) to build a Java classpath and list of properties and configuration files to pass to the main class of the Jetty XML configuration mechanism. The start.jar mechanism has many options which are documented in the [startup] administration section and you can see them in summary by using the command:

> java -jar $JETTY_HOME/start.jar --help

Deploying Web Applications

Jetty server instances that configure the deploy module will have a web application deployer that hot deploys files found in the webapps directory. Standard WAR files and Jetty configuration files that are placed in the webapps directory are hot deployed to the server with the following conventions:

  • A directory called example/ is deployed as a standard web application if it contains a WEB-INF/ subdirectory, otherwise it is deployed as context of static content. The context path is /example (that is, http://localhost:8080/example/) unless the base name is ROOT (case insensitive), in which case the context path is /. If the directory name ends with ".d" it is ignored (but may be used by explicit configuration).

  • A file called example.war is deployed as a standard web application with the context path /example (that is, http://localhost:8080/example/). If the base name is ROOT (case insensitive), the context path is /. If example.war and example/ exist, only the WAR is deployed (which may use the directory as an unpack location).

  • An XML file like example.xml is deployed as a context whose configuration is defined by the XML. The configuration itself must set the context path. If example.xml and example.war exists, only the XML is deployed (which may use the WAR in its configuration).

If you have a standard web application, you can hot deploy it into Jetty by copying it into the webapps directory.

Jetty Demonstration Web Applications

The demo-base/webapps directory contains the following deployable and auxiliary files:

ROOT/

A directory of static content that is deployed to the root context / due to it’s name. Contains the Jetty demo welcome page.

test.d

A directory containing additional configuration files used by test.xml to inject extra configuration into test.war.

test.xml

A context configuration file that configures and deploys test.war. The additional configuration includes the context path as well as setting additional descriptors found in the test.d directory.

test.war

The demonstration web application that is configured and deployed by test.xml.

async-rest.war

A web application demonstration of asynchronous REST to eBay, automatically deployed to /async-rest based on the file name.

test-jaas.war

A demonstration web application utilizing JAAS for authentication.

test-jaas.xml

A context configuration file that configures test-jaas.war. Additional configuration includes setting up the LoginService for authentication and authorization.

test-jndi.war

A demonstration web application showing the use of JNDI.

test-jndi.xml

A context configuration file that configures test-jndi.war. Additional configuration includes defining objects in the naming space that can be referenced from the webapp.

test-spec.war

A demonstration web application that shows the use of annotations, fragments, ServletContainerInitializers and other Servlet Specification 3.0/3.1 features.

test-spec.xml

A context configuration file that configures test-spec.war. Additional configuration includes setting up some objects in the naming space that can be referenced by annotations.

javadoc-proxy.war

A demonstration web application that uses a transparent proxy to serve the Jetty source Javadoc from the Eclipse Jetty website.

example-moved.xml

A demonstration context configuration file that shows how to use the MovedContextHandler to redirect from one path to another.

An Introduction to Jetty Configuration

How to Configure Jetty

To understand Jetty configuration, you need to understand the "How" and the "What". This section covers how to configure Jetty in terms of what mechanisms exist to perform configuration. The next section gives an overview of the action components and fields that you can configure with these mechanisms.

Jetty POJO Configuration

The core components of Jetty are Plain Old Java Objects (POJOs) The process of configuring Jetty is mostly the process of instantiating, assembling and setting fields on the Jetty POJOs. This can be achieved by:

  • Writing Java code to directly instantiate and assemble Jetty objects. This is referred to as [embedding-jetty].

  • Using Jetty XML configuration, which is an Inversion of Control (IoC) framework, to instantiate and assemble Jetty objects as XML objects. The etc/jetty.xml file is the main Jetty XML configuration file, but there are many other etc/jetty-feature.xml files included in the Jetty distribution.

  • Using a third party IoC framework like Spring, to instantiate and assemble Jetty objects as Spring beans.

Because the main Jetty configuration is done by IoC, the Jetty API documentation is the ultimate configuration reference.

Jetty Start Configuration Files

The Jetty distribution uses the following configuration files to instantiate, inject and start server via the start.jar mechanism.

ini files

The Jetty Start mechanism uses the command line, the $JETTY_BASE/start.ini and/or $JETTY_BASE/start.d/*.ini files to create an effective command line of arguments. Arguments may be:

  • Module activations in the form --module=name

  • Properties in the form of name=value, used to parameterize Jetty IoC XML

  • XML files in Jetty IoC (or Spring) XML format

  • A standard Java property file containing additional start properties

  • Other start.jar options (see java -jar start.jar --help)

  • Some JVM options in combination with --exec, such as -Xbootclasspath.

It is the ini files located in the Jetty base directory (if different from Jetty home) that are typically edited to change the configuration (e.g. change ports).

mod files

The $JETTY_HOME/modules/*.mod files contain the definition of modules that can be activated by --module=name. Each mod file defines:

  • Module dependencies for ordering and activation

  • The libraries needed by the module to be added to the classpath

  • The XML files needed by the module to be added to the effective command line

  • Files needed by the activated module

  • A template ini file to be used when activating the --add-to-start=name option

    Typically module files are rarely edited and only then for significant structural changes. The .mod files are normally located in $JETTY_HOME/modules/, but extra or edited modules may be added to $JETTY_BASE/module. If module changes are required, it is best practice to copy the particular .mod file from $JETTY_HOME/modules/ to $JETTY_BASE/modules/ before being modified.

XML files

XML files in Jetty IoC XML format or Spring IoC format are listed either on the command line, in ini files, or are added to the effective command line by a module definition. The XML files instantiate and inject the actual Java objects that comprise the server, connectors and contexts. Because Jetty IoC XML files use properties, most common configuration tasks can be accomplished without editing these XML files and can instead be achieved by editing the property in the corresponding ini files. XML files are normally located in $JETTY_HOME/etc/, but extra or edited XML files may be added to $JETTY_BASE/etc/. Note If XML configuration changes are required, it is best practice to copy the XML file from $JETTY_HOME/etc/ to $JETTY_BASE/etc/ before being modified.

Below is an illustration of how the various Jetty configuration files (ini, mod and XML) are related:

image

A Closer Look

To put it simply: XML files are responsible for instantiating the Jetty POJOs that make up the server. They define properties which users can modify to meet the needs of their server. These XML files are broken up by type in the distribution so they can be consumed as a user/server needs them. For example, a server may need HTTP and HTTPS functionality, but opt out of using HTTP/2 and Websocket.

Module files allow users to enable and remove functionality quickly and easily from their server implementation. They include a template of the different properties included in the associated XML file, as well as a pointer to the XML or JAR file(s) they are referencing. When a module is activated these properties are added to a related ini file where users can configure them to meet their needs. We will discuss modules in further detail in an upcoming chapter.

Ini files are where most users will spend the bulk of their time editing the configuration for their server. As mentioned, they contain properties which were defined in their associated XML files which in turn reference Jetty Java objcts.

This can be a bit overwhelming at first, so let’s look at an example - in this case the http module. We will work backwards from an ini file to the associated module and then the XML file in question.

First up, the http.ini file. If we take a look at it’s contents, we will see the following:

$ cat start.d/http.ini
# ---------------------------------------
# Module: http
# Enables a HTTP connector on the server.
# By default HTTP/1 is support, but HTTP2C can
# be added to the connector with the http2c module.
# ---------------------------------------
--module=http

### HTTP Connector Configuration

## Connector host/address to bind to
# jetty.http.host=0.0.0.0

## Connector port to listen on
# jetty.http.port=8080

## Connector idle timeout in milliseconds
# jetty.http.idleTimeout=30000

## Number of acceptors (-1 picks default based on number of cores)
# jetty.http.acceptors=-1

## Number of selectors (-1 picks default based on number of cores)
# jetty.http.selectors=-1

## ServerSocketChannel backlog (0 picks platform default)
# jetty.http.acceptorQueueSize=0

## Thread priority delta to give to acceptor threads
# jetty.http.acceptorPriorityDelta=0

## Reserve threads for high priority tasks (-1 use a heuristic, 0 no reserved threads)
# jetty.http.reservedThreads=-1

## Connect Timeout in milliseconds
# jetty.http.connectTimeout=15000

## HTTP Compliance: RFC7230, RFC2616, LEGACY
# jetty.http.compliance=RFC7230

So what do we see? We have a module name, the module activation (--module=http), as well as a description and what look like properties to configure. Those will some scripting/coding experience might notice that most of the lines are commented out with # and you’d be correct. When a module is enabled and an ini file is created, all of the properties you see here were set to these defaults - the server is already using the values shown If you wanted to change one of the properties though, say jetty.http.port, you’d simply uncomment the line and change the value. For example:

$ cat start.d/http.ini
# ---------------------------------------
# Module: http
# Enables a HTTP connector on the server.
# By default HTTP/1 is support, but HTTP2C can
# be added to the connector with the http2c module.
# ---------------------------------------
--module=http

### HTTP Connector Configuration

## Connector host/address to bind to
# jetty.http.host=0.0.0.0

## Connector port to listen on
jetty.http.port=1234
...

As seen before, these properties were populated in this ini file based on a related module. Standard Jetty modules live in the Home of the Jetty Distribution in the aptly named modules directory. So let’s take a quick look at the associated $JETTY_HOME/modules/http.mod file:

$ cat $JETTY_HOME/modules/http.mod
[description]
Enables a HTTP connector on the server.
By default HTTP/1 is support, but HTTP2C can
be added to the connector with the http2c module.

[tags]
connector
http

[depend]
server

[xml]
etc/jetty-http.xml

[ini-template]
### HTTP Connector Configuration

## Connector host/address to bind to
# jetty.http.host=0.0.0.0

## Connector port to listen on
# jetty.http.port=8080

## Connector idle timeout in milliseconds
# jetty.http.idleTimeout=30000
...

At first blush, it looks remarkable similar to the ini file we just looked at. We still have a description and the properties we could edit, but now we also have several other sections. These other sections will be looked at further in our chapter on modules, but for now it is worth noting the [xml] and [ini-template] sections. As you could probably have puzzled out, the [ini-template] contains a template (go figure) for properties to be placed in the associated ini file when a module is activated. The [xml] section refers to the file and location of the XML file these properties are based on. It is important to note that not every module file will have the same sections, but most should look structurally the same.

Now that we know what XML file these properties relate to, we can navigate to it and have a look.

$ cat $JETTY_HOME/etc/jetty-http.xml
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "https://www.eclipse.org/jetty/configure_9_3.dtd">

<!-- ============================================================= -->
<!-- Configure the Jetty Server instance with an ID "Server"       -->
<!-- by adding a HTTP connector.                                   -->
<!-- This configuration must be used in conjunction with jetty.xml -->
<!-- ============================================================= -->
<Configure id="Server" class="org.eclipse.jetty.server.Server">

  <!-- =========================================================== -->
  <!-- Add a HTTP Connector.                                       -->
  <!-- Configure an o.e.j.server.ServerConnector with a single     -->
  <!-- HttpConnectionFactory instance using the common httpConfig  -->
  <!-- instance defined in jetty.xml                               -->
  <!--                                                             -->
  <!-- Consult the javadoc of o.e.j.server.ServerConnector and     -->
  <!-- o.e.j.server.HttpConnectionFactory for all configuration    -->
  <!-- that may be set here.                                       -->
  <!-- =========================================================== -->
  <Call name="addConnector">
    <Arg>
      <New id="httpConnector" class="org.eclipse.jetty.server.ServerConnector">
        <Arg name="server"><Ref refid="Server" /></Arg>
        <Arg name="acceptors" type="int"><Property name="jetty.http.acceptors" deprecated="http.acceptors" default="-1"/></Arg>
        <Arg name="selectors" type="int"><Property name="jetty.http.selectors" deprecated="http.selectors" default="-1"/></Arg>
        <Arg name="factories">
          <Array type="org.eclipse.jetty.server.ConnectionFactory">
            <Item>
              <New class="org.eclipse.jetty.server.HttpConnectionFactory">
                <Arg name="config"><Ref refid="httpConfig" /></Arg>
                <Arg name="compliance"><Call class="org.eclipse.jetty.http.HttpCompliance" name="valueOf"><Arg><Property name="jetty.http.compliance" default="RFC7230"/></Arg></Call></Arg>
              </New>
            </Item>
          </Array>
        </Arg>
        <Set name="host"><Property name="jetty.http.host" deprecated="jetty.host" /></Set>
        <Set name="port"><Property name="jetty.http.port" deprecated="jetty.port" default="8080" /></Set>
        <Set name="idleTimeout"><Property name="jetty.http.idleTimeout" deprecated="http.timeout" default="30000"/></Set>
        <Set name="acceptorPriorityDelta"><Property name="jetty.http.acceptorPriorityDelta" deprecated="http.acceptorPriorityDelta" default="0"/></Set>
        <Set name="acceptQueueSize"><Property name="jetty.http.acceptQueueSize" deprecated="http.acceptQueueSize" default="0"/></Set>
        <Get name="SelectorManager">
          <Set name="connectTimeout"><Property name="jetty.http.connectTimeout" default="15000"/></Set>
          <Set name="reservedThreads"><Property name="jetty.http.reservedThreads" default="-2"/></Set>
        </Get>
      </New>
    </Arg>
  </Call>

</Configure>

Now we can see where those properties in our ini and module files came from. In Jetty XML files, Jetty objects come to life; defined properties are set which link back to the jar libraries and run the server to a user’s specification.

It is important to remember that you should not modify the XML files in your $JETTY_HOME. If you do for some reason feel you want to change the way an XML file operates, it is best to make a copy of it in your $JETTY_BASE in an /etc directory. Jetty will always look first to the $JETTY_BASE for configuration.

Other Configuration Files

In addition to the configuration files described above, the configuration of the server can use the following file types:

Context XML files

Any XML files in Jetty IoC XML format or Spring IoC format that is discovered in the /webapps directory are used by the deploy module to instantiate and inject HttpContext instances to create a specific context. These may be standard web applications or bespoke contexts created from special purpose handlers.

web.xml

The Servlet Specification defines the web.xml deployment descriptor that defines and configures the filters, servlets and resources a web application uses. The Jetty WebAppContext component uses this XML format to:

  • Set up the default configuration of a web application context.

  • Interpret the application-specific configuration supplied with a web application in the WEB-INF/web.xml file.

  • Interpret descriptor fragments included in the META-INF directory of Jar files within WEB-INF/lib.

    Normally the web.xml file for a web application is found in the WEB-INF/web.xml location within the war file/directory or as web.xml fragments with .jar files found in WEB-INF/lib. Jetty also supports multiple web.xml files so that a default descriptor may be applied before WEB-INF/web.xml (typically set to etc/webdefault.xml by the deploy module) and an override descriptor may be applied after WEB-INF/web.xml (typically set by a context XML file see test.xml)

Property Files

Standard Java property files are also used for Jetty configuration in several ways:

  • To parameterize Jetty IoC XML via the use of the Property element.

  • To configure the default logging mechanism (StdErrLog). Other logging frameworks can be utilized and also use property files (for example, log4j).

  • As a simple database for login usernames and credentials.

Jetty IoC XML format

To understand the Jetty IoC XML format, consider the following example of an embedded Jetty server instantiated and configured in Java:

//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//

package org.eclipse.jetty.embedded;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;

public class ExampleServer
{
    public static Server createServer(int port)
    {
        Server server = new Server();

        ServerConnector connector = new ServerConnector(server);
        connector.setPort(port);
        server.setConnectors(new Connector[]{connector});

        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        context.addServlet(HelloServlet.class, "/hello");
        context.addServlet(AsyncEchoServlet.class, "/echo/*");

        HandlerCollection handlers = new HandlerCollection();
        handlers.setHandlers(new Handler[]{context, new DefaultHandler()});
        server.setHandler(handlers);

        return server;
    }

    public static void main(String[] args) throws Exception
    {
        int port = ExampleUtil.getPort(args, "jetty.http.port", 8080);
        Server server = createServer(port);
        server.start();
        server.join();
    }
}

Jetty IoC XML format allows you to instantiate and configure the exact same server in XML without writing any java code:

<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "https://www.eclipse.org/jetty/configure_9_3.dtd">

<Configure id="ExampleServer" class="org.eclipse.jetty.server.Server">

  <Set name="connectors">
    <Array type="org.eclipse.jetty.server.Connector">
      <Item>
        <New class="org.eclipse.jetty.server.ServerConnector">
          <Arg><Ref refid="ExampleServer"/></Arg>
          <Set name="port">
            <Property name="http.port" default="8080" />
          </Set>
        </New>
      </Item>
    </Array>
  </Set>

  <New id="context" class="org.eclipse.jetty.servlet.ServletContextHandler">
    <Set name="contextPath">/hello</Set>
    <Call name="addServlet">
      <Arg>org.eclipse.jetty.embedded.HelloServlet</Arg>
      <Arg>/</Arg>
    </Call>
  </New>

  <Set name="handler">
    <New class="org.eclipse.jetty.server.handler.HandlerCollection">
      <Set name="handlers">
        <Array type="org.eclipse.jetty.server.Handler">
          <Item>
            <Ref refid="context" />
          </Item>
          <Item>
            <New class="org.eclipse.jetty.server.handler.DefaultHandler" />
          </Item>
        </Array>
      </Set>
    </New>
  </Set>
</Configure>

What to Configure in Jetty

This section gives an overview of the components of Jetty you typically configure using the mechanisms outlined in the previous section. [basic-architecture] describes the structure of a Jetty server, which is good background reading to understand configuration, and is vital if you want to change the structure of the server as set up by the default configurations in the Jetty distribution. However, for most purposes, configuration is a matter of identifying the correct configuration file and modifying existing configuration values.

Configuring the Server

The Server instance is the central coordination object of a Jetty server; it provides services and life cycle management for all other Jetty server components. In the standard Jetty distribution, the core server configuration is in etc/jetty.xml file, but you can mix in other server configurations which can include:

ThreadPool

The Server instance provides a ThreadPool instance that is the default Executor service other Jetty server components use. The prime configuration of the thread pool is the maximum and minimum size and is set in start.ini or start.d/server.ini.

Handlers

A Jetty server can have only a single Handler instance to handle incoming HTTP requests. However a handler may be a container or wrapper of other handlers forming a tree of handlers that typically handle a request as a collaboration between the handlers from a branch of the tree from root to leaf. The default handler tree set up in the etc/jetty.xml file is a Handler Collection containing a Context Handler Collection and the Default Handler. The Context Handler Collection selects the next handler by context path and is where deployed Context Handler and Web Application Contexts are added to the handler tree. The Default Handler handles any requests not already handled and generates the standard 404 page. Other configuration files may add handlers to this tree (for example, jetty-rewrite.xml, jetty-requestlog.xml) or configure components to hot deploy handlers (for example, jetty-deploy.xml).

Server Attributes

The server holds a generic attribute map of strings to objects so that other Jetty components can associate named objects with the server, and if the value objects implement the LifeCycle interface, they are started and stopped with the server. Typically server attributes hold server-wide default values.

Server fields

The server also has some specific configuration fields that you set in start.ini or start.d/server.ini for controlling, among other things, the sending of dates and versions in HTTP responses.

Connectors

The server holds a collection of connectors that receive connections for HTTP and the other protocols that Jetty supports. The next section, Configuring Connectors describes configuration of the connectors themselves. For the server you can either set the collection of all connectors or add/remove individual connectors.

Services

The server can hold additional service objects, sometimes as attributes, but often as aggregated LifeCycle beans. Examples of services are Login Services and DataSources, which you configure at the server level and then inject into the web applications that use them.

Configuring Connectors

A Jetty Server Connector is a network end point that accepts connections for one or more protocols which produce requests and/or messages for the Jetty server. In the standard Jetty server distribution, several provided configuration files add connectors to the server for various protocols and combinations of protocols: http.ini, https.ini and jetty-http2.xml. The configuration needed for connectors is typically:

Port

The TCP/IP port on which the connector listens for connections is set using the the XML Property element which looks up the jetty.http.port (or jetty.ssl.port) property, and if not found defaults to 8080 (or 8443 for TLS).

Host

You can configure a host either as a host name or IP address to identify a specific network interface on which to listen. If not set, or set to the value of 0.0.0.0, the connector listens on all local interfaces. The XML Property element is used to look up the host value from the jetty.host property.

Idle Timeout

The time in milliseconds that a connection can be idle before the connector takes action to close the connection.

HTTP Configuration

Connector types that accept HTTP semantics (including HTTP, HTTPS and HTTP2) are configured with a HttpConfiguration instance that contains common HTTP configuration that is independent of the specific wire protocol used. Because these values are often common to multiple connector types, the standard Jetty Server distribution creates a single HttpConfiguration in the jetty.xml file which is used via the XML Ref element in the specific connector files.

SSL Context Factory

The TLS connector types (HTTPS and HTTP2) configure an SSL Context Factory with the location of the server keystore and truststore for obtaining server certificates.

Virtual hosts are not configured on connectors. You must configure individual contexts with the virtual hosts to which they respond.
Prior to Jetty 9, the type of the connector reflected both the protocol supported (HTTP, HTTPS, AJP, SPDY), and the nature of the implementation (NIO or BIO). From Jetty 9 onwards there is only one prime Connector type (ServerConnector), which is NIO based and uses Connection Factories to handle one or more protocols.

Configuring Contexts

A Jetty context is a handler that groups other handlers under a context path together with associated resources and is roughly equivalent to the standard ServletContext API. A context may contain either standard Jetty handlers or a custom application handler.

The servlet specification defines a web application. In Jetty a standard web application is a specialized context that uses a standard layout and WEB-INF/web.xml to instantiate and configure classpath, resource base and handlers for sessions, security, and servlets, plus servlets for JSPs and static content. Standard web applications often need little or no additional configuration, but you can also use the techniques for arbitrary contexts to refine or modify the configuration of standard web applications.

Configuration values that are common to all contexts are:

contextPath

The contextPath is a URL prefix that identifies which context a HTTP request is destined for. For example, if a context has a context path /foo, it handles requests to /foo, /foo/index.html, /foo/bar/, and /foo/bar/image.png but it does not handle requests like /, /other/, or /favicon.ico. A context with a context path of / is called the root context.

The context path can be set by default from the deployer (which uses the filename as the basis for the context path); or in code; or it can be set by a Jetty IoC XML that is either applied by the deployer or found in the WEB-INF/jetty-web.xml file of a standard web app context.

virtualHost

A context may optionally have one or more virtual hosts set. Unlike the host set on a connector (which selects the network interface on which to listen), a virtual host does not set any network parameters. Instead a virtual host represents an alias assigned by a name service to an IP address, which may have many aliases. To determine which virtual host a request is intended for, the HTTP client (browser) includes in the request the name used to look up the network address. A context with a virtual host set only handles requests that have a matching virtual host in their request headers.

classPath

A context may optionally have a classpath, so that any thread that executes a handler within the context has a thread context classloader set with the classpath. A standard web application has the classpath initialized by the WEB-INF/lib and WEB-INF/classes directory and has additional rules about delegating classloading to the parent classloader. All contexts may have additional classpath entries added.

attributes

Attributes are arbitrary named objects that are associated with a context and are frequently used to pass entities between a web application and its container. For example the attribute javax.servlet.context.tempdir is used to pass the File instance that represents the assigned temporary directory for a web application.

resourceBase

The resource base is a directory (or collection of directories or URL) that contains the static resources for the context. These can be images and HTML files ready to serve or JSP source files ready to be compiled. In traditional web servers this value is often called the docroot.

Context Configuration by API

In an embedded server, you configure contexts by directly calling the ContextHandler API as in the following example:

//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//

package org.eclipse.jetty.embedded;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;

public class OneContext
{
    public static Server createServer(int port)
    {
        Server server = new Server(port);

        // Add a single handler on context "/hello"
        ContextHandler context = new ContextHandler();
        context.setContextPath("/hello");
        context.setHandler(new HelloHandler());

        // Can be accessed using http://localhost:8080/hello

        server.setHandler(context);
        return server;
    }

    public static void main(String[] args) throws Exception
    {
        int port = ExampleUtil.getPort(args, "jetty.http.port", 8080);
        Server server = createServer(port);

        // Start the server
        server.start();
        server.join();
    }
}
Context Configuration by IoC XML

You can create and configure a context entirely by IoC XML (either Jetty’s or Spring). The deployer discovers and hot deploys context IoC descriptors like the following which creates a context to serve the Javadoc from the Jetty distribution:

<?xml version="1.0"  encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "https://www.eclipse.org/jetty/configure_9_3.dtd">

<!--
  Configure a custom context for serving javadoc as static resources
-->

<Configure class="org.eclipse.jetty.server.handler.ContextHandler">
  <Set name="contextPath">/javadoc</Set>
  <Set name="resourceBase"><SystemProperty name="jetty.home" default="."/>/javadoc/</Set>
  <Set name="handler">
    <New class="org.eclipse.jetty.server.handler.ResourceHandler">
      <Set name="welcomeFiles">
        <Array type="String">
          <Item>index.html</Item>
        </Array>
      </Set>
      <Set name="cacheControl">max-age=3600,public</Set>
    </New>
  </Set>
</Configure>
Configuring Web Applications

The servlet specification defines a web application, which when packaged as a zip is called WAR file (Web application ARchive). Jetty implements both WAR files and unpacked web applications as a specialized context that is configured by means of:

  • A standard layout which sets the location of the resourceBase (the root of the WAR) and initializes the classpath from jars found in WEB-INF/lib and classes found in WEB-INF/classes.

  • The standard WEB-INF/web.xml deployment descriptor which is parsed to define and configure init parameters, filters, servlets, listeners, security constraints, welcome files and resources to be injected.

  • A default web.xml format deployment descriptor provided either by Jetty or in configuration configures the JSP servlet and the default servlet for handling static content. The standard web.xml may override the default web.xml.

  • Annotations discovered on classes in Jars contained in WEB-INF/lib can declare additional filters, servlets and listeners.

  • Standard deployment descriptor fragments discovered in Jars contained in WEB-INF/lib can declare additional init parameters, filters, servlets, listeners, security constraints, welcome files and resources to be injected.

  • An optional WEB-INF/jetty-web.xml file may contain Jetty IoC configuration to configure the Jetty specific APIs of the context and handlers.

Because these configuration mechanisms are contained within the WAR file (or unpacked web application), typically a web application contains much of its own configuration and deploying a WAR is often just a matter of dropping the WAR file in to the webapps directory that is scanned by the Jetty deployer.

If you need to configure something within a web application, often you do so by unpacking the WAR file and editing the web.xml and other configuration files. However, both the servlet standard and some Jetty features allow for other configuration to be applied to a web application externally from the WAR:

  • Configured data sources and security realms in the server can be injected into a web application either explicitly or by name matching.

  • Jetty allows one or more override deployment descriptors, in web.xml format, to be set on a context (via code or IoC XML) to amend the configuration set by the default and standard web.xml.

  • The normal Jetty Java API may be called by code or IoC XML to amend the configuration of a web application.

Setting the Context Path

The web application standard provides no configuration mechanism for a web application or WAR file to set its own contextPath. By default the deployer uses conventions to set the context path: If you deploy a WAR file called foobar.WAR, the context path is /foobar; if you deploy a WAR file called ROOT.WAR the context path is /.

However, it is often desirable to explicitly set the context path so that information (for example, version numbers) may be included in the filename of the WAR. Jetty allows the context Path of a WAR file to be set internally (by the WAR itself) or externally (by the deployer of the WAR).

To set the contextPath from within the WAR file, you can include a WEB-INF/jetty-web.xml file which contains IoC XML to set the context path:

<?xml version="1.0"  encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "https://www.eclipse.org/jetty/configure_9_3.dtd">

<Configure class="org.eclipse.jetty.webapp.WebAppContext">
    <Set name="contextPath">/contextpath</Set>
</Configure>

Alternately, you can configure the classpath externally without the need to modify the WAR file itself. Instead of allowing the WAR file to be discovered by the deployer, an IoC XML file may be deployed that both sets the context path and declares the WAR file that it applies to:

<?xml version="1.0"  encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "https://www.eclipse.org/jetty/configure_9_3.dtd">

<Configure class="org.eclipse.jetty.webapp.WebAppContext">
  <Set name="war"><SystemProperty name="jetty.home" default="."/>/webapps/test.war</Set>
  <Set name="contextPath">/test</Set>
</Configure>

An example of setting the context path is included with the Jetty distribution in $JETTY_HOME/webapps/test.xml.

Web Application Deployment

Jetty is capable of deploying a variety of Web Application formats. This is accomplished via scans of the ${jetty.base}/webapps directory for contexts to deploy.

A Context can be any of the following:

  • A standard WAR file. (must in “.war”).

  • A directory containing an expanded WAR file. (must contain {dir}/WEB-INF/web.xml file).

  • A directory containing static content.

  • A XML descriptor in [jetty-xml-syntax] that configures a ContextHandler instance (Such as a WebAppContext).

The new WebAppProvider will attempt to avoid double deployments during the directory scan with the following heuristics:

  • Hidden files (starting with ".") are ignored

  • Directories with names ending in ".d" are ignored

  • If a directory and matching WAR file exist with the same base name (eg: foo/ and foo.war), then the directory is assumed to be the unpacked WAR and only the WAR is deployed (which may reuse the unpacked directory)

  • If a directory and matching XML file exists (eg: foo/ and foo.xml), then the directory is assumed to be an unpacked WAR and only the XML is deployed (which may use the directory in its own configuration)

  • If a WAR file and matching XML file exist (eg: foo.war and foo.xml), then the WAR is assumed to be configured by the XML and only the XML is deployed.

In prior versions of Jetty there was a separate ContextDeployer that provided XML-based deployment. As of Jetty 9 the ContextDeployer no longer exists and its functionality has been merged with the new WebAppProvider to avoid double deployment scenarios.
Setting an Authentication Realm

The authentication method and realm name for a standard web application may be set in the web.xml deployment descriptor with elements like:

...
<login-config>
  <auth-method>BASIC</auth-method>
  <realm-name>Test Realm</realm-name>
</login-config>
...

This example declares that the BASIC authentication mechanism will be used with credentials validated against a realm called "Test Realm." However the standard does not describe how the realm itself is implemented or configured. In Jetty, there are several realm implementations (called LoginServices) and the simplest of these is the HashLoginService, which can read usernames and credentials from a Java properties file.

To configure an instance of HashLoginService that matches the "Test Realm" configured above, the following $JETTY_BASE/etc/test-realm.xml IoC XML file should be passed on the command line or set in start.ini or start.d/server.ini.

<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "https://www.eclipse.org/jetty/configure_10_0.dtd">
<Configure id="Server" class="org.eclipse.jetty.server.Server">
  <!-- =========================================================== -->
  <!-- Configure Authentication Login Service                      -->
  <!-- Realms may be configured for the entire server here, or     -->
  <!-- they can be configured for a specific web app in a context  -->
  <!-- configuration (see $(jetty.home)/webapps/test.xml for an    -->
  <!-- example).                                                   -->
  <!-- =========================================================== -->
  <Call name="addBean">
    <Arg>
      <New class="org.eclipse.jetty.security.HashLoginService">
        <Set name="name">Test Realm</Set>
        <Set name="config">
          <Property name="jetty.demo.realm" default="etc/realm.properties" />
        </Set>
        <Set name="hotReload">false</Set>
      </New>
    </Arg>
  </Call>

  <Call class="org.slf4j.LoggerFactory" name="getLogger">
    <Arg>org.eclipse.jetty</Arg>
    <Call name="warn">
      <Arg>demo test-realm is deployed. DO NOT USE IN PRODUCTION!</Arg>
    </Call>
  </Call>
</Configure>

This creates and configures the LoginService as an aggregate bean on the server. When a web application is deployed that declares a realm called "Test Realm," the server beans are searched for a matching Login Service.