This example is very similar to the one in the previous section, although it enables the embedded webapp to use JSPs.
As of jetty-9.2, we use the JSP engine from Apache, which relies on a Servlet Specification 3.1 style ServletContainerInitializer to initialize itself.
As of jetty-9.2, we use the JSP engine from Apache, which relies on a Servlet Specification 3.1 style `ServletContainerInitializer` to initialize itself.
To get this to work with Jetty, you need to enable annotations processing, as shown in this example code:
[source, java, subs="{sub-order}"]
@ -52,7 +52,7 @@ After you have started things up you should be able to navigate to http://localh
===== Maven Coordinates
To use this example in your project, you will need the following maven dependencies declared, in addition to those from the previous section:
To use this example in your project, you will need the following Maven dependencies declared, in addition to those from the previous section:
One or more handlers do all request handling in Jetty.
Some handlers select other specific handlers (for example, a ContextHandlerCollection uses the context path to select a ContextHandler); others use application logic to generate a response (for example, the ServletHandler passes the request to an application Servlet), while others do tasks unrelated to generating the response (for example, RequestLogHandler or StatisticsHandler).
Some handlers select other specific handlers (for example, a `ContextHandlerCollection` uses the context path to select a `ContextHandler`); others use application logic to generate a response (for example, the `ServletHandler` passes the request to an application Servlet), while others do tasks unrelated to generating the response (for example, `RequestLogHandler` or `StatisticsHandler`).
Later sections describe how you can combine handlers like aspects.
You can see some of the handlers available in Jetty in the link:{JXURL}/org/eclipse/jetty/server/handler/package-summary.html[org.eclipse.jetty.server.handler] package.
@ -92,28 +92,28 @@ You can see some of the handlers available in Jetty in the link:{JXURL}/org/ecli
===== Handler Collections and Wrappers
Complex request handling is typically built from multiple Handlers that you can combine in various ways.
Jetty has several implementations of the link:{JDURL}/org/eclipse/jetty/server/HandlerContainer.html[HandlerContainer] interface:
Jetty has several implementations of the link:{JDURL}/org/eclipse/jetty/server/HandlerContainer.html[`HandlerContainer`] interface:
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.
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.
You can use it to combine handlers that conditionally handle a request, such as calling multiple contexts until one matches a virtual host.
A specialized HandlerCollection that uses the longest prefix of the request URI (the contextPath) to select a contained ContextHandler to handle the request.
A specialized `HandlerCollection` that uses the longest prefix of the request URI (the `contextPath`) to select a contained `ContextHandler` to handle the request.
===== Scoped Handlers
Much of the standard Servlet container in Jetty is implemented with HandlerWrappers that daisy chain handlers together: ContextHandler to SessionHandler to SecurityHandler to ServletHandler.
Much of the standard Servlet container in Jetty is implemented with `HandlerWrappers` that daisy chain handlers together: `ContextHandler` to `SessionHandler` to `SecurityHandler` to `ServletHandler`.
However, because of the nature of the servlet specification, this chaining cannot be a pure nesting of handlers as the outer handlers sometimes need information that the inner handlers process.
For example, when a ContextHandler calls some application listeners to inform them of a request entering the context, it must already know which servlet the ServletHandler will dispatch the request to so that the servletPath method returns the correct value.
For example, when a `ContextHandler` calls some application listeners to inform them of a request entering the context, it must already know which servlet the `ServletHandler` will dispatch the request to so that the `servletPath` method returns the correct value.
The HandlerWrapper is specialized to the link:{JXURL}/org/eclipse/jetty/server/handler/ScopedHandler.html[ScopedHandler] abstract class, which supports a daisy chain of scopes.
For example if a ServletHandler is nested within a ContextHandler, the order and nesting of execution of methods is:
The `HandlerWrapper` is specialized to the link:{JXURL}/org/eclipse/jetty/server/handler/ScopedHandler.html[`ScopedHandler`] abstract class, which supports a daisy chain of scopes.
For example if a `ServletHandler` is nested within a `ContextHandler`, the order and nesting of execution of methods is:
....
Server.handle(...)
@ -124,23 +124,23 @@ Server.handle(...)
SomeServlet.service(...)
....
Thus when the ContextHandler handles the request, it does so within the scope the ServletHandler has established.
Thus when the `ContextHandler` handles the request, it does so within the scope the `ServletHandler` has established.
===== Resource Handler
The link:{JXURL}/org/eclipse/jetty/embedded/FileServer.html[FileServer example] shows how you can use a ResourceHandler to serve static content from the current working directory:
The link:{JXURL}/org/eclipse/jetty/embedded/FileServer.html[FileServer example] shows how you can use a `ResourceHandler` to serve static content from the current working directory:
Notice that a HandlerList is used with the ResourceHandler and a DefaultHandler, so that the DefaultHandler generates a good 404 response for any requests that do not match a static resource.
Notice that a `HandlerList` is used with the `ResourceHandler` and a `DefaultHandler`, so that the `DefaultHandler` generates a good 404 response for any requests that do not match a static resource.
==== Embedding Connectors
In the previous examples, the Server instance is passed a port number and it internally creates a default instance of a Connector that listens for requests on that port.
However, often when embedding Jetty it is desirable to explicity instantiate and configure one or more Connectors for a Server instance.
However, often when embedding Jetty it is desirable to explicitly instantiate and configure one or more Connectors for a Server instance.
===== One Connector
@ -152,24 +152,24 @@ instantiates, configures, and adds a single HTTP connector instance to the serve
In this example the connector handles the HTTP protocol, as that is the default for the link:{JXURL}/org/eclipse/jetty/server/ServerConnector.html[ServerConnector] class.
In this example the connector handles the HTTP protocol, as that is the default for the link:{JXURL}/org/eclipse/jetty/server/ServerConnector.html[`ServerConnector`] class.
===== Many Connectors
When configuring multiple connectors (for example, HTTP and HTTPS), it may be desirable to share configuration of common parameters for HTTP.
To achieve this you need to explicitly configure the ServerConnector class with ConnectionFactory instances, and provide them with common HTTP configuration.
To achieve this you need to explicitly configure the `ServerConnector` class with `ConnectionFactory` instances, and provide them with common HTTP configuration.
The link:{JXURL}/org/eclipse/jetty/embedded/ManyConnectors.html[ManyConnectors example], configures a server with two ServerConnector instances: the http connector has a link:{JXURL}/org/eclipse/jetty/server/HttpConnectionFactory.html[HTTPConnectionFactory] instance; the https connector has a SslConnectionFactory chained to a HttpConnectionFactory.
Both HttpConnectionFactories are configured based on the same link:{JXURL}/org/eclipse/jetty/server/HttpConfiguration.html[HttpConfiguration] instance, however the HTTPS factory uses a wrapped configuration so that a link:{JXURL}/org/eclipse/jetty/server/SecureRequestCustomizer.html[SecureRequestCustomizer] can be added.
The link:{JXURL}/org/eclipse/jetty/embedded/ManyConnectors.html[ManyConnectors example], configures a server with two `ServerConnector` instances: the http connector has a link:{JXURL}/org/eclipse/jetty/server/HttpConnectionFactory.html[`HTTPConnectionFactory`] instance; the https connector has a `SslConnectionFactory` chained to a `HttpConnectionFactory`.
Both `HttpConnectionFactory` are configured based on the same link:{JXURL}/org/eclipse/jetty/server/HttpConfiguration.html[`HttpConfiguration`] instance, however the HTTPS factory uses a wrapped configuration so that a link:{JXURL}/org/eclipse/jetty/server/SecureRequestCustomizer.html[`SecureRequestCustomizer`] can be added.
==== Embedding Servlets
http://en.wikipedia.org/wiki/Java_Servlet[Servlets] are the standard way to provide application logic that handles HTTP requests.
Servlets are similar to a Jetty Handler except that the request object is not mutable and thus cannot be modified.
Servlets are handled in Jetty by a link:{JXURL}/org/eclipse/jetty/embedded/MinimalServlets.html[ServletHandler].
It uses standard path mappings to match a Servlet to a request; sets the requests servletPath and pathInfo; passes the request to the servlet, possibly via Filters to produce a response.
Servlets are handled in Jetty by a link:{JXURL}/org/eclipse/jetty/embedded/MinimalServlets.html[`ServletHandler`].
It uses standard path mappings to match a Servlet to a request; sets the requests `servletPath` and `pathInfo`; passes the request to the servlet, possibly via Filters to produce a response.
The link:{JXURL}/org/eclipse/jetty/embedded/MinimalServlets.html[MinimalServlets example] creates a ServletHandler instance and configures a single HelloServlet:
The link:{JXURL}/org/eclipse/jetty/embedded/MinimalServlets.html[MinimalServlets example] creates a `ServletHandler` instance and configures a single HelloServlet:
A link:{JXURL}/org/eclipse/jetty/embedded/OneContext.html[ContextHandler] is a ScopedHandler that responds only to requests that have a URI prefix that matches the configured context path.
A link:{JXURL}/org/eclipse/jetty/embedded/OneContext.html[`ContextHandler`] is a `ScopedHandler` that responds only to requests that have a URI prefix that matches the configured context path.
Requests that match the context path have their path methods updated accordingly and the contexts scope is available, which optionally may include:
* A Classloader that is set as the Thread context classloader while request handling is in scope.
* A set of attributes that is available via the http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html[ServletContext] API.
* A set of init parameters that is available via the http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html[ServletContext] API.
* A base Resource which is used as the document root for static resource requests via the http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html[ServletContext] API.
* A `Classloader` that is set as the Thread context `classloader` while request handling is in scope.
* A set of attributes that is available via the http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html[`ServletContext`] API.
* A set of init parameters that is available via the http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html[`ServletContext`] API.
* A base Resource which is used as the document root for static resource requests via the http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html[`ServletContext`] API.
* A set of virtual host names.
The following link:{JXURL}/org/eclipse/jetty/embedded/OneContext.html[OneContext example] shows a context being established that wraps the link:{JXURL}/org/eclipse/jetty/embedded/HelloHandler.html[HelloHandler]:
@ -194,7 +194,7 @@ The following link:{JXURL}/org/eclipse/jetty/embedded/OneContext.html[OneContext
When many contexts are present, you can embed a ContextHandlerCollection to efficiently examine a request URI to then select the matching ContextHandler(s) for the request.
When many contexts are present, you can embed a `ContextHandlerCollection` to efficiently examine a request URI to then select the matching `ContextHandler`(s) for the request.
The link:{JXURL}/org/eclipse/jetty/embedded/ManyContexts.html[ManyContexts example] shows how many such contexts you can configure:
A link:{JXURL}/org/eclipse/jetty/servlet/ServletContextHandler.html[ServletContextHandler] is a specialization of ContextHandler with support for standard sessions and Servlets.
The following link:{JXURL}/org/eclipse/jetty/embedded/OneServletContext.html[OneServletContext example] instantiates a link:{JXURL}/org/eclipse/jetty/servlet/DefaultServlet.html[DefaultServlet] to server static content from /tmp/ and a `DumpServlet` that creates a session and dumps basic details about the request:
A link:{JXURL}/org/eclipse/jetty/servlet/ServletContextHandler.html[`ServletContextHandler`] is a specialization of `ContextHandler` with support for standard sessions and Servlets.
The following link:{JXURL}/org/eclipse/jetty/embedded/OneServletContext.html[OneServletContext example] instantiates a link:{JXURL}/org/eclipse/jetty/servlet/DefaultServlet.html[`DefaultServlet`] to server static content from /tmp/ and a `DumpServlet` that creates a session and dumps basic details about the request:
A link:{JXURL}/org/eclipse/jetty/webapp/WebAppContext.html[WebAppContext] is an extension of a ServletContextHandler that uses the http://en.wikipedia.org/wiki/WAR_%28Sun_file_format%29[standard layout] and web.xml to configure the servlets, filters and other features from a web.xml and/or annotations.
A link:{JXURL}/org/eclipse/jetty/webapp/WebAppContext.html[`WebAppContext`] is an extension of a `ServletContextHandler` that uses the http://en.wikipedia.org/wiki/WAR_%28Sun_file_format%29[standard layout] and web.xml to configure the servlets, filters and other features from a web.xml and/or annotations.
The following link:{JXURL}/org/eclipse/jetty/embedded/OneWebApp.html[OneWebApp example] configures the Jetty test webapp.
Web applications can use resources the container provides, and in this case a LoginService is needed and also configured:
Web applications can use resources the container provides, and in this case a `LoginService` is needed and also configured:
The typical way to configure an instance of the Jetty server is via `jetty.xml` and associated configuration files.
However the Jetty XML configuration format is just a simple rendering of what you can do in code; it is very simple to write embedded code that does precisely what the jetty.xml configuration does.
The link:{JXURL}/org/eclipse/jetty/embedded/LikeJettyXml.html[LikeJettyXml example] following renders in code the behaviour obtained from the configuration files:
The link:{JXURL}/org/eclipse/jetty/embedded/LikeJettyXml.html[LikeJettyXml example] following renders in code the behavior obtained from the configuration files:
This example shows how to create a simple file server in Jetty.
It is perfectly suitable for test cases where you need an actual web server to obtain a file from, it could easily be configured to serve files from a directory under src/test/resources.
It is perfectly suitable for test cases where you need an actual web server to obtain a file from, it could easily be configured to serve files from a directory under `src/test/resources`.
Note that this does not have any logic for caching of files, either within the server or setting the appropriate headers on the response.
It is simply a few lines that illustrate how easy it is to serve out some files.
@ -34,7 +34,7 @@ After you have started things up you should be able to navigate to http://localh
===== Maven Coordinates
To use this example in your project you will need the following maven dependencies declared.
To use this example in your project you will need the following Maven dependencies declared.
This example shows the bare minimum required for deploying a servlet into jetty.
This example shows the bare minimum required for deploying a servlet into Jetty.
Note that this is strictly a servlet, not a servlet in the context of a web application, that example comes later.
This is purely just a servlet deployed and mounted on a context and able to process requests.
This example is excellent for situations where you have a simple servlet that you need to unit test, just mount it on a context and issue requests using your favorite http client library (like our Jetty client found in xref:http-client[]).
Start things up! By using the server.join() the server thread will join with the current thread.
See http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()[Thread.join()] for more details.
Start things up! By using the `server.join()` the server thread will join with the current thread.
See link:http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()[`Thread.join()`] for more details.
It is really simple to create useful servlets for testing behaviors, sometimes you just need a http server to run a unit test against that will return test content and wiring up a servlet like this makes it trivial.
It is really simple to create useful servlets for testing behaviors. Sometimes you need a http server to run a unit test against that will return test content and wiring up a servlet like this makes it trivial.
After you have started things up you should be able to navigate to http://localhost:8080/ and you are good to go.
===== Maven Coordinates
To use this example in your project you will need the following maven dependencies declared.
To use this example in your project you will need the following Maven dependencies declared.
This example shows how to deploy a simple webapp with an embedded instance of jetty.
This example shows how to deploy a simple webapp with an embedded instance of Jetty.
This is useful when you want to manage the lifecycle of a server programmatically, either within a production application or as a simple way to deploying and debugging a full scale application deployment.
In many ways it is easier then traditional deployment since you control the classpath yourself, making this easy to wire up in a test case in maven and issue requests using your favorite http client library (like our Jetty client found in xref:http-client[]).
In many ways it is easier then traditional deployment since you control the classpath yourself, making this easy to wire up in a test case in Maven and issue requests using your favorite http client library (like our Jetty client found in xref:http-client[]).
[source, java, subs="{sub-order}"]
----
@ -33,7 +33,7 @@ After you have started things up you should be able to navigate to http://localh
===== Maven Coordinates
To use this example in your project you will need the following maven dependencies declared.
To use this example in your project you will need the following Maven dependencies declared.
This example shows how to wrap one handler with another one that handles security.
We have a simple Hello Handler that just return a greeting but add on the restriction that to get this greeting you must authenticate.
Another thing to remember is that this example uses the ConstraintSecurityHandler which is what supports the security mappings inside of the servlet api, it could be easier to show just the SecurityHandler usage, but the constraint provides more configuration power.
If you don't need that you can drop the Constraint bits and use just the SecurityHandler.
Another thing to remember is that this example uses the `ConstraintSecurityHandler` which is what supports the security mappings inside of the servlet api, it could be easier to show just the `SecurityHandler` usage, but the constraint provides more configuration power.
If you don't need that you can drop the Constraint bits and use just the `SecurityHandler`.
This example builds on the link:#emebedded-file-server[Simple File Server] to show how chaining multiple ResourceHandlers together can let you aggregate mulitple directories to serve content on a single path and how you can link these together with ContextHandlers.
This example builds on the link:#emebedded-file-server[Simple File Server] to show how chaining multiple `ResourceHandlers` together can let you aggregate multiple directories to serve content on a single path and how you can link these together with `ContextHandlers`.
@ -24,11 +24,11 @@ This section provides a tutorial that shows how you can quickly develop embedded
Jetty is decomposed into many jars and dependencies to achieve a minimal footprint by selecting the minimal set of jars.
Typically it is best to use something like Maven to manage jars, however this tutorial uses an aggregate Jar that contains all of the Jetty classes in one Jar.
You can manually download the aggregate http://central.maven.org/maven2/org/eclipse/jetty/aggregate/jetty-all/{VERSION}/jetty-all-{VERSION}-uber.jar[`jetty-all.jar`] using `curl`) or a browser.
You can manually download the aggregate link:http://central.maven.org/maven2/org/eclipse/jetty/aggregate/jetty-all/{VERSION}/jetty-all-{VERSION}-uber.jar[`jetty-all.jar`] using `curl`) or a browser.
____
[NOTE]
The central maven repository has started to aggressively reject/deny access to the repository from the `wget` command line tool (due to abusive use of the tool by some groups).
The central Maven repository has started to aggressively reject/deny access to the repository from the `wget` command line tool (due to abusive use of the tool by some groups).
The administrators of the central maven repository have stated that the recommended command line download tool is now curl.
____
@ -82,5 +82,5 @@ You can now point your browser at http://localhost:8080/[http://localhost:8080]
To learn more about Jetty, take these next steps:
* Follow the examples in link:#embedding-jetty[Embedding Jetty] to better understand the jetty APIs.
* Explore the complete link:{JDURL}/[jetty javadoc]
* Explore the complete link:{JDURL}/[Jetty javadoc]
* Consider using link:#maven-and-jetty[Jetty and Maven] to manage your Jars and dependencies.