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.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.
36 // Note that if you set this to port 0 then a randomly available port
37 // will be assigned that you can either look in the logs for the port,
38 // or programmatically obtain it for use in test cases.
39 Server server = new Server(8080);
40
41 // The ServletHandler is a dead simple way to create a context handler
42 // that is backed by an instance of a Servlet.
43 // This handler then needs to be registered with the Server object.
44 ServletHandler handler = new ServletHandler();
45 server.setHandler(handler);
46
47 // Passing in the class for the Servlet allows jetty to instantiate an
48 // instance of that Servlet and mount it on a given context path.
49
50 // IMPORTANT:
51 // This is a raw Servlet, not a Servlet that has been configured
52 // through a web.xml @WebServlet annotation, or anything similar.
53 handler.addServletWithMapping(HelloServlet.class, "/*");
54
55 // Start things up!
56 server.start();
57
58 // The use of server.join() the will make the current thread join and
59 // wait until the server is done executing.
60 // See
61 // http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join()
62 server.join();
63 }
64
65 @SuppressWarnings("serial")
66 public static class HelloServlet extends HttpServlet
67 {
68 @Override
69 protected void doGet( HttpServletRequest request,
70 HttpServletResponse response ) throws ServletException,
71 IOException
72 {
73 response.setContentType("text/html");
74 response.setStatus(HttpServletResponse.SC_OK);
75 response.getWriter().println("<h1>Hello from HelloServlet</h1>");
76 }
77 }
78 }