1 //
2 // ========================================================================
3 // Copyright (c) 1995-2014 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.io.IOException;
22
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServlet;
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
27
28 import org.eclipse.jetty.server.Server;
29 import org.eclipse.jetty.servlet.ServletHandler;
30
31 public class MinimalServlets
32 {
33 public static void main(String[] args) throws Exception
34 {
35 // Create a basic jetty server object that will listen on port 8080. Note that if you set this to port 0
36 // then a randomly available port will be assigned that you can either look in the logs for the port,
37 // or programmatically obtain it for use in test cases.
38 Server server = new Server(8080);
39
40 // The ServletHandler is a dead simple way to create a context handler that is backed by an instance of a
41 // Servlet. This handler then needs to be registered with the Server object.
42 ServletHandler handler = new ServletHandler();
43 server.setHandler(handler);
44
45 // Passing in the class for the servlet allows jetty to instantite an instance of that servlet and mount it
46 // on a given context path.
47
48 // !! This is a raw Servlet, not a servlet that has been configured through a web.xml or anything like that !!
49 handler.addServletWithMapping(HelloServlet.class, "/*");
50
51 // Start things up! By using the server.join() the server thread will join with the current thread.
52 // See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more details.
53 server.start();
54 server.join();
55 }
56
57 @SuppressWarnings("serial")
58 public static class HelloServlet extends HttpServlet
59 {
60 @Override
61 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
62 {
63 response.setContentType("text/html");
64 response.setStatus(HttpServletResponse.SC_OK);
65 response.getWriter().println("<h1>Hello SimpleServlet</h1>");
66 }
67 }
68 }