View Javadoc

1   // ========================================================================
2   // Copyright (c) 2006-2009 Mort Bay Consulting Pty. Ltd.
3   // ------------------------------------------------------------------------
4   // All rights reserved. This program and the accompanying materials
5   // are made available under the terms of the Eclipse Public License v1.0
6   // and Apache License v2.0 which accompanies this distribution.
7   // The Eclipse Public License is available at 
8   // http://www.eclipse.org/legal/epl-v10.html
9   // The Apache License v2.0 is available at
10  // http://www.opensource.org/licenses/apache2.0.php
11  // You may elect to redistribute this code under either of these licenses. 
12  // ========================================================================
13  
14  package org.eclipse.jetty.embedded;
15  
16  import java.io.IOException;
17  
18  import javax.servlet.ServletException;
19  import javax.servlet.http.HttpServletRequest;
20  import javax.servlet.http.HttpServletResponse;
21  
22  import org.eclipse.jetty.server.Request;
23  import org.eclipse.jetty.server.Server;
24  import org.eclipse.jetty.server.handler.AbstractHandler;
25  import org.eclipse.jetty.server.handler.ContextHandler;
26  
27  
28  /* ------------------------------------------------------------ */
29  /**
30   * A {@link ContextHandler} provides a common environment for
31   * multiple Handlers, such as: URI context path, class loader,
32   * static resource base.
33   *
34   * Typically a ContextHandler is used only when multiple contexts
35   * are likely.
36   */
37  public class OneContext
38  {
39      public static void main(String[] args)
40      throws Exception
41      {
42          Server server = new Server(8080);
43          
44          ContextHandler context = new ContextHandler();
45          context.setContextPath("/");
46          context.setResourceBase(".");
47          context.setClassLoader(Thread.currentThread().getContextClassLoader());
48          server.setHandler(context);
49          
50          context.setHandler(new HelloHandler());
51          
52          server.start();
53          server.join();
54      }
55      
56      public static class HelloHandler extends AbstractHandler
57      {
58          public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
59          {
60              response.setStatus(HttpServletResponse.SC_OK);
61              response.setContentType("text/html");
62              response.getWriter().println("<h1>Hello OneContext</h1>");
63              ((Request)request).setHandled(true);
64          }
65      }
66  }