Search code examples
javaservletsjetty-9

multiple servlet in jetty


I am new to Jetty and trying to understand by online example program. Here is the sample program I used:

public class EmbeddedJettyMain {

    public static void main(String[] args) throws Exception {

        Server server = new Server(7070);
        ServletContextHandler handler = new ServletContextHandler(server, "/example");
        handler.addServlet(ExampleServlet.class, "/");
        server.start();

    }

}

With that I can use:

http://localhost:7070/example/

Now I want to add one more servlet URI

http://localhost:7070/example2

How can I do this ?

I can see some reference such as webapp, looking for a good approach.


Solution

  • Server server = new Server(7070);
    ServletContextHandler handler = new ServletContextHandler(server, "/");
    handler.addServlet(ExampleServlet.class, "/example");
    handler.addServlet(ExampleServlet.class, "/example2");
    

    Each addServlet creates a mapping. Jetty will create an instance of the Servlet that will be a singleton for each mapping, meaning that init(ServletConfig config) will only be called once in each instance and all requests to a mapping go to the same instance.