View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.embedded;
20  
21  import java.lang.management.ManagementFactory;
22  
23  import org.eclipse.jetty.jmx.MBeanContainer;
24  import org.eclipse.jetty.server.Server;
25  import org.eclipse.jetty.server.handler.ContextHandlerCollection;
26  import org.eclipse.jetty.servlet.DefaultServlet;
27  import org.eclipse.jetty.servlet.ServletContextHandler;
28  import org.eclipse.jetty.servlet.ServletHolder;
29  
30  public class ManyServletContexts
31  {
32      public static void main( String[] args ) throws Exception
33      {
34          Server server = new Server(8080);
35  
36          // Setup JMX
37          MBeanContainer mbContainer = new MBeanContainer(
38                  ManagementFactory.getPlatformMBeanServer());
39          server.addBean(mbContainer, true);
40  
41          // Declare server handler collection
42          ContextHandlerCollection contexts = new ContextHandlerCollection();
43          server.setHandler(contexts);
44  
45          // Configure context "/" (root) for servlets
46          ServletContextHandler root = new ServletContextHandler(contexts, "/",
47                  ServletContextHandler.SESSIONS);
48          // Add servlets to root context
49          root.addServlet(new ServletHolder(new HelloServlet("Hello")), "/");
50          root.addServlet(new ServletHolder(new HelloServlet("Ciao")), "/it/*");
51          root.addServlet(new ServletHolder(new HelloServlet("Bonjoir")), "/fr/*");
52  
53          // Configure context "/other" for servlets
54          ServletContextHandler other = new ServletContextHandler(contexts,
55                  "/other", ServletContextHandler.SESSIONS);
56          // Add servlets to /other context
57          other.addServlet(DefaultServlet.class.getCanonicalName(), "/");
58          other.addServlet(new ServletHolder(new HelloServlet("YO!")), "*.yo");
59  
60          server.start();
61          server.join();
62      }
63  }