Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

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

Line 100: Line 100:
  
 
         SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();
 
         SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector();
         String jetty_home = System.getProperty("jetty.home","../jetty-distribution/target/distribution");
+
         String jetty_home =  
 +
          System.getProperty("jetty.home","../jetty-distribution/target/distribution");
 
         System.setProperty("jetty.home",jetty_home);
 
         System.setProperty("jetty.home",jetty_home);
 
         ssl_connector.setPort(8443);
 
         ssl_connector.setPort(8443);
Line 202: Line 203:
 
}
 
}
 
</pre>
 
</pre>
 
  
 
== ServletContext ==
 
== ServletContext ==
 +
 +
 +
<pre>
 +
public class OneServletContext
 +
{
 +
    public static void main(String[] args) throws Exception
 +
    {
 +
        Server server = new Server(8080);
 +
 +
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
 +
        context.setContextPath("/");
 +
        server.setHandler(context);
 +
 +
        context.addServlet(new ServletHolder(new HelloServlet()),"/*");
 +
 +
        server.start();
 +
        server.join();
 +
    }
 +
}
 +
</pre>
  
 
== WebApplicationContext ==
 
== WebApplicationContext ==
  
 
}}
 
}}

Revision as of 06:47, 27 July 2009



Introduction

Jetty has a slogan "Don't deploy your application in Jetty, deploy Jetty in your application". What this means is that Jetty as an alternative to bundling your application as a standard WAR to be deployed in Jetty, Jetty is designed to be a software component that can be instantiated and used in a java program just like any POJO.

This tutorial takes you step by step from the simplest jetty server instantiation, through programmatically, to running multiple web applications with standards based deployment descriptors.

The source for most of these examples is part of the standard jetty project.

Details

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

  1. Create the server
  2. Add/Configure Connectors
  3. Add/Configure Handlers
  4. Add/Configure Servlets/Webapps to Handlers
  5. start the server
  6. wait (join the server to prevent main exiting).

Servers

The following code from SimplestServer.java will instantiate and run the simplest possible Jetty server:

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

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


Handlers

In order to produce a response to a request, Jetty requires a Handler to be set on the server. A handler may:


Hello World Handler

The following code based on HelloHandler.java shows a simple hello world handler:

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

The parameters passed to the handle method are:

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

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

The following code from OneHandler.java shows how this handler can be used by a Jetty server:

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

You now know everything you need to know to write a HTTP server based on Jetty. However, complex request handling is typically built from multiple Handlers and we will look in later sections how handlers can be combined like aspects. Some of the handlers available in Jetty can be seen in the org.eclipse.jetty.server.handler package.

Connectors

In order to configure the HTTP connectors used by the server, one or more Connectors may be set on the server. Each connector may be configured with details such as interface, port, buffer sizes, timeouts etc.

The following code is based on ManyConnectors.java and shows how connectors may be set and configured for the Hello world example:

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

        SelectChannelConnector connector0 = new SelectChannelConnector();
        connector0.setPort(8080);
        connector0.setMaxIdleTime(30000);
        connector0.setRequestHeaderSize(8192);

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

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

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

        server.setHandler(new HelloHandler());

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

Handler Collections, wrappers and Scopes

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

  • A Handler Collection holds a collection of other handlers and will call each handler in order. This is useful for combining statistics and logging handlers with the handler that generates the response.
  • A Handler List is a Handler Collection that calls each handler in turn until either an exception is thrown, the response is committed or the request.isHandled() returns true. It can be used to combine handlers that conditionally handle a request.
  • A Handler Wrapper is a handler base class that can be use to daisy chain handlers together in the style of aspect oriented programming. For example, a standard web application is implemented by a chain of a context, session, security and servlet handlers.
  • A Context Handler Collection uses the longest prefix of the request URI (the contextPath) to select a specific ContextHandler to handle the request.

File Server

The following code from FileServer.java uses a HandlerList to combine the ResourceHandler with the DefaultHandler:

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

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

        resource_handler.setResourceBase(".");
        
        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
        server.setHandler(handlers);

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

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

Contexts

A ContextHandler is a HandlerWrapper that will respond only to requests that have a URI prefix that match the configured context path.

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

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

Requests that don't match are not handled.

The following code is based on OneContext.java and sets context path and classloader for the hello handler:

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

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

        context.setHandler(new HelloHandler());

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

Servlets

Servlets are the standard way to provide application logic that handles HTTP requests. Servlets are like constrained Handlers with standard ways to map specific URIs to specific servlets. The following code is based on HelloServlet.java:

public class HelloServlet extends HttpServlet
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println("<h1>Hello World</h1>");
        response.getWriter().println("session=" + request.getSession(true).getId());
    }
}

ServletContext

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

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);

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

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

WebApplicationContext

Back to the top