Sie sind auf Seite 1von 11

24/03/2011 Jetty/Tutorial/Embedding Jetty - Eclip…

Jetty/Tutorial/Embedding Jetty
From Eclipsepedia

< Jetty | Tutorial


Getting Started Features Tutorials HowTos Reference FAQ Contribute

Jetty Home (http://eclipse.org/jetty)

Contents
1 Introduction
2 Details
3 Creating a Server
4 Writing Handlers
4.1 Hello World Handler
5 Configuring Connectors
6 Understanding Handler Collections, Wrappers and Scopes
7 Configuring a File Server
7.1 Configuring a File Server with XML
7.2 Using Spring to Configure a File Server
8 Setting Contexts
9 Creating Servlets
10 Setting a ServletContext
11 Setting a Web Application Context
12 Configuring a Context Handler Collection
13 Embedding JSP

Introduction
Jetty has a slogan, "Don't deploy your application in Jetty, deploy Jetty in your application." What this means is that
as an alternative to bundling your application as a standard WAR to be deployed in Jetty, Jetty is designed to be a
software component that can be instantiated and used in a Java program just like any POJO
(http://en.wikipedia.org/wiki/Plain_Old_Java_Object) .

This tutorial takes you step-by-step from the simplest Jetty server instantiation to running multiple web applications
with standards-based deployment descriptors.

The source (http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/embedded/package-summary.html) for


most of these examples is part of the standard Jetty project.

This tutorial is also available as a Embedding Jetty Webinar recording (http://vimeo.com/19146453) .

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

1. Create the server


2. Add/Configure Connectors
3. Add/Configure Handlers

wiki.eclipse.org/…/Embedding_Jetty 1/11
24/03/2011 Jetty/Tutorial/Embedding Jetty - Eclip…
4. Add/Configure Servlets/Webapps to Handlers
5. Start the server
6. Wait (join the server to prevent main exiting)

Creating a Server
The following code from SimplestServer.java (http://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk/example-
jetty-embedded/src/main/java/org/eclipse/jetty/embedded/SimplestServer.java) instantiates and runs the simplest
possible Jetty server:

public class SimplestServer


{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
server.start();
server.join();
}
}

This runs an HTTP server on port 8080. It is not a very useful server as it has no handlers and thus returns a 404
error for every request.

Writing Handlers
To produce a response to a request, Jetty requires a Handler (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/server/Handler.html) to be set on the server. A handler may:

examine/modify the HTTP request.


generate the complete HTTP response.
call another Handler (see HandlerWrapper (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/server/handler/HandlerWrapper.html) ).
Select one or many Handlers to call (see HandlerCollection (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/server/handler/HandlerCollection.html) ).

Hello World Handler

The following code based on HelloHandler.java


(http://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk/example-jetty-
embedded/src/main/java/org/eclipse/jetty/embedded/HelloHandler.java) shows a simple hello world handler:

public class HelloHandler extends AbstractHandler


{
public void handle(String target,Request baseRequest,HttpServletRequest request,
throws IOException, ServletException
{
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("<h1>Hello World</h1>");
}
}

wiki.eclipse.org/…/Embedding_Jetty 2/11
24/03/2011 Jetty/Tutorial/Embedding Jetty - Eclip…
The parameters passed to the handle method are:

target–the target of the request, which is either a URI or a name from a named dispatcher.
baseRequest–the Jetty mutable request object, which is always unwrapped.
request–the immutable request object, which may have been wrapped.
response–the response, which may have been wrapped.

The handler sets the response status, content-type and marks the request as handled before it generates the body
of the response using a writer.

The following code from OneHandler.java (http://download.eclipse.org/jetty/stable-


7/xref/org/eclipse/jetty/embedded/OneHandler.html) shows how a Jetty server can use this handler:

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


{
Server server = new Server(8080);
server.setHandler(new HelloHandler());

server.start();
server.join();
}

You now know everything you need to know to write an HTTP server based on Jetty. However, complex request
handling is typically built from multiple Handlers. We will look in later sections at how handlers can be combined
like aspects. You can see some of the handlers available in Jetty in the org.eclipse.jetty.server.handler
(http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/package-frame.html) package.

Configuring Connectors
To configure the HTTP connectors that the server uses, you can set one or more connector
(http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/Connector.html) s on the server. You can
configure each connector with details such as interface, port, buffer sizes, timeouts, etc.

The following code is based on ManyConnectors.java (http://download.eclipse.org/jetty/stable-


7/xref/org/eclipse/jetty/embedded/ManyConnectors.html) and shows how to set and configure connectors for the
Hello World example:

wiki.eclipse.org/…/Embedding_Jetty 3/11
24/03/2011 Jetty/Tutorial/Embedding Jetty - Eclip…

public class ManyConnectors


{
public static void main(String[] args) throws Exception
{
Server server = new Server();

SelectChannelConnector connector0 = new SelectChannelConnector();


connector0.setPort(8080);
connector0.setMaxIdleTime(30000);
connector0.setRequestHeaderSize(8192);

SelectChannelConnector connector1 = new SelectChannelConnector();


connector1.setHost("127.0.0.1");
connector1.setPort(8888);
connector1.setThreadPool(new QueuedThreadPool(20));
connector1.setName("admin");

SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();


String jetty_home =
System.getProperty("jetty.home","../jetty-distribution/target/distribution
System.setProperty("jetty.home",jetty_home);
ssl_connector.setPort(8443);
ssl_connector.setKeystore(jetty_home + "/etc/keystore");
ssl_connector.setPassword("OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4");
ssl_connector.setKeyPassword("OBF:1u2u1wml1z7s1z7a1wnl1u2g");
server.addConnector(ssl_connector);

server.setConnectors(new Connector[]{ connector0, connector1, ssl_connector

server.setHandler(new HelloHandler());

server.start();
server.join();
}
}

Understanding Handler Collections, Wrappers and Scopes


Complex request handling is typically built from multiple Handlers that can be combined in various ways:

A Handler Collection (http://download.eclipse.org/jetty/stable-


7/xref/org/eclipse/jetty/server/handler/HandlerCollection.html) holds a collection of other handlers and calls
each handler in order. This is useful for combining statistics and logging handlers with the handler that
generates the response.
A Handler List (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/server/handler/HandlerList.html) is a Handler Collection that calls each handler in
turn until either an exception is thrown, the response is committed or the request.isHandled() returns true. It
can be used to combine handlers that conditionally handle a request.
A Handler Wrapper (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/server/handler/HandlerWrapper.html) is a handler base class that can be used to
daisy chain handlers together in the style of aspect-oriented programming. For example, a standard web
application is implemented by a chain of a context, session, security and servlet handlers.
A Context Handler Collection (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/server/handler/ContextHandlerCollection.html) uses the longest prefix of the request
URI (the contextPath) to select a specific ContextHandler (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/server/handler/ContextHandler.html) to handle the request.

wiki.eclipse.org/…/Embedding_Jetty 4/11
24/03/2011 Jetty/Tutorial/Embedding Jetty - Eclip…
See also How to Write a Jetty Handler.

Configuring a File Server


The following code from FileServer.java (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/embedded/FileServer.html) uses a HandlerList to combine the ResourceHandler
(http://download.eclipse.org/jetty/stable-7/xref/org/eclipse/jetty/server/handler/ResourceHandler.html) with the
DefaultHandler (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/server/handler/DefaultHandler.html) :

public class FileServer


{
public static void main(String[] args) throws Exception
{
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);

ResourceHandler resource_handler = new ResourceHandler();


resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[]{ "index.html" });

resource_handler.setResourceBase(".");

HandlerList handlers = new HandlerList();


handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler()
server.setHandler(handlers);

server.start();
server.join();
}
}

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

Configuring a File Server with XML

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

wiki.eclipse.org/…/Embedding_Jetty 5/11
24/03/2011 Jetty/Tutorial/Embedding Jetty - Eclip…

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

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

<Call name="addConnector">
<Arg>
<New class="org.eclipse.jetty.server.nio.SelectChannelConnector">
<Set name="port">8080</Set>
</New>
</Arg>
</Call>

<Set name="handler">
<New class="org.eclipse.jetty.server.handler.HandlerList">
<Set name="handlers">
<Array type="org.eclipse.jetty.server.Handler">
<Item>
<New class="org.eclipse.jetty.server.handler.ResourceHandler">
<Set name="directoriesListed">true</Set>
<Set name="welcomeFiles">
<Array type="String"><Item>index.html</Item></Array>
</Set>
<Set name="resourceBase">.</Set>
</New>
</Item>
<Item>
<New class="org.eclipse.jetty.server.handler.DefaultHandler">
</New>
</Item>
</Array>
</Set>
</New>
</Set>
</Configure>

This XML file can be run from the FileServerXml.java


(http://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk/example-jetty-
embedded/src/main/java/org/eclipse/jetty/embedded/FileServerXml.java) class:

public class FileServerXml


{
public static void main(String[] args) throws Exception
{
Resource fileserver_xml = Resource.newSystemResource("fileserver.xml");
XmlConfiguration configuration = new XmlConfiguration(fileserver_xml.getInpu
Server server = (Server)configuration.configure();
server.start();
server.join();
}
}

Using Spring to Configure a File Server

You can also use the Spring framework to assemble Jetty servers. The file server example above can be written in
wiki.eclipse.org/…/Embedding_Jetty 6/11
24/03/2011 Jetty/Tutorial/Embedding Jetty - Eclip…
Spring configuration as:

<beans>
<bean id="Server" class="org.eclipse.jetty.server.Server" init-method="start" dest

<property name="connectors">
<list>
<bean id="Connector" class="org.eclipse.jetty.server.nio.SelectChannelConnec
<property name="port" value="8080"/>
</bean>
</list>
</property>

<property name="handler">
<bean id="handlers" class="org.eclipse.jetty.server.handler.HandlerList">
<property name="handlers">
<list>
<bean class="org.eclipse.jetty.server.handler.ResourceHandler">
<property name="directoriesListed" value="true"/>
<property name="welcomeFiles">
<list>
<value>index.html</value>
</list>
</property>
<property name="resourceBase" value="."/>
</bean>
<bean class="org.eclipse.jetty.server.handler.DefaultHandler"/>
</list>
</property>
</bean>
</property>
</bean>
</beans>

See also How to Configure Jetty with Spring.

Setting Contexts
A ContextHandler (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/server/handler/ContextHandler.html) is a HandlerWrapper that responds only to requests
that have a URI prefix that matches the configured context path.

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

* A Thread Context classloader.


* A set of attributes
* A set of init parameters
* A resource base (aka document root)
* A set of virtual host names

Requests that don't match are not handled.

The following code is based on OneContext.java (http://download.eclipse.org/jetty/stable-


7/xref/org/eclipse/jetty/embedded/OneContext.html) and sets context path and classloader for the hello handler:

wiki.eclipse.org/…/Embedding_Jetty 7/11
24/03/2011 Jetty/Tutorial/Embedding Jetty - Eclip…

public class OneContext


{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);

ContextHandler context = new ContextHandler();


context.setContextPath("/hello");
context.setResourceBase(".");
context.setClassLoader(Thread.currentThread().getContextClassLoader());
server.setHandler(context);

context.setHandler(new HelloHandler());

server.start();
server.join();
}
}

Creating Servlets
Servlets are the standard way to provide application logic that handles HTTP requests. Servlets are like
constrained Handlers with standard ways to map specific URIs to specific servlets. The following code is based on
HelloServlet.java (http://dev.eclipse.org/svnroot/rt/org.eclipse.jetty/jetty/trunk/example-jetty-
embedded/src/main/java/org/eclipse/jetty/embedded/HelloServlet.java) :

public class HelloServlet extends HttpServlet


{
private String greeting="Hello World";
public HelloServlet(){}
public HelloServlet(String greeting)
{
this.greeting=greeting;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) t
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>"+greeting+"</h1>");
response.getWriter().println("session=" + request.getSession(true).getId());
}
}

Setting a ServletContext
A ServletContextHandler (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/servlet/ServletContextHandler.html) is a specialization of ContextHandler with support for
standard servlets. The following code from OneServletContext (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/embedded/OneServletContext.html) shows 3 instances of the helloworld servlet registered
with a ServletContextHandler:

wiki.eclipse.org/…/Embedding_Jetty 8/11
24/03/2011 Jetty/Tutorial/Embedding Jetty - Eclip…

public class OneServletContext


{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);

ServletContextHandler context = new ServletContextHandler(ServletContextHand


context.setContextPath("/");
server.setHandler(context);

context.addServlet(new ServletHolder(new HelloServlet()),"/*");


context.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),"
context.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),"

server.start();
server.join();
}
}

Setting a Web Application Context


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

public class OneWebApp


{
public static void main(String[] args) throws Exception
{
String jetty_home = System.getProperty("jetty.home","..");

Server server = new Server(8080);

WebAppContext webapp = new WebAppContext();


webapp.setContextPath("/");
webapp.setWar(jetty_home+"/webapps/test.war");
server.setHandler(webapp);

server.start();
server.join();
}
}

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

wiki.eclipse.org/…/Embedding_Jetty 9/11
24/03/2011 Jetty/Tutorial/Embedding Jetty - Eclip…

public class OneWebAppUnassembled


{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);

WebAppContext context = new WebAppContext();


context.setDescriptor(webapp+"/WEB-INF/web.xml");
context.setResourceBase("../test-jetty-webapp/src/main/webapp");
context.setContextPath("/");
context.setParentLoaderPriority(true);

server.setHandler(context);

server.start();
server.join();
}
}

Configuring a Context Handler Collection


A Context Handler Collection (http://download.eclipse.org/jetty/stable-
7/xref/org/eclipse/jetty/server/handler/ContextHandlerCollection.html) uses the longest prefix of the request URI
(the contextPath) to select a specific context. The following example combines the previous two examples in a
single Jetty server:

public class ManyContexts


{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);

ServletContextHandler context0 = new ServletContextHandler(ServletContextHan


context0.setContextPath("/ctx0");
context0.addServlet(new ServletHolder(new HelloServlet()),"/*");
context0.addServlet(new ServletHolder(new HelloServlet("Buongiorno Mondo")),
context0.addServlet(new ServletHolder(new HelloServlet("Bonjour le Monde")),

WebAppContext webapp = new WebAppContext();


webapp.setContextPath("/ctx1");
webapp.setWar(jetty_home+"/webapps/test.war");

ContextHandlerCollection contexts = new ContextHandlerCollection();


contexts.setHandlers(new Handler[] { context0, webapp });

server.setHandler(contexts);

server.start();
server.join();
}
}

Embedding JSP

wiki.eclipse.org/…/Embedding_Jetty 10/11
24/03/2011 Jetty/Tutorial/Embedding Jetty - Eclip…
Embedding jsp support can be a bit confusing if you look at the jars under the lib/jsp directory in the jetty
distribution. This is because we have to ship from eclipse with the jsp bundles that are marked up as osgi bundles
and these are not directly downloadable from maven central. There are dependencies available in maven central
that will work though as they are the ones that were the actual source for the osgi bundles themselves. The osgi
bundles are simply these maven central artifacts that have been decomposed into a few extra bundles.

Below is an example of what could be used.

[INFO] org.eclipse.jetty:jetty-jsp-2.1:jar:7.2.2-SNAPSHOT
[INFO] +- org.eclipse.jetty:jetty-util:jar:7.2.2-SNAPSHOT:provided
[INFO] +- org.mortbay.jetty:jsp-2.1-glassfish:jar:2.1.v20100127:provided
[INFO] | +- org.eclipse.jdt.core.compiler:ecj:jar:3.5.1:provided
[INFO] | +- org.mortbay.jetty:jsp-api-2.1-glassfish:jar:2.1.v20100127:provided
[INFO] | \- ant:ant:jar:1.6.5:provided
[INFO] \- javax.servlet:servlet-api:jar:2.5:provided

You should be able to depend on one of the embedding aggregates that we provide to get these dependencies
without too much trouble.

http://repo2.maven.org/maven2/org/eclipse/jetty/aggregate

Retrieved from "http://wiki.eclipse.org/Jetty/Tutorial/Embedding_Jetty"

Categories: Jetty | Jetty Tutorial

Home
Privacy Policy
Terms of Use
Copyright Agent
Contact
About Eclipsepedia

Copyright © 2011 The Eclipse Foundation. All Rights Reserved

This page was last modified 20:34, 18 February 2011 by Shirley Boulay. Based on work by Greg Wilkins,
Jesse McConnell and Michael Buck and others.

This page has been accessed 108,964 times.

wiki.eclipse.org/…/Embedding_Jetty 11/11

Das könnte Ihnen auch gefallen