Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migration from Jetty 6 to Jetty 8

I use jetty6 in simple application as embedded servlet container. I decided to update it to Jetty 8. In jetty 6 it was pretty simple to start the server:

Server server = new Server(8080);
Context context = new Context(server, "/", Context.SESSIONS);
context.addServlet(MyServlet.class, "/communication-service");
server.start();

but it doesn't work in Jetty8. Unfortunately I can't find any simple example for this version. Can't instantiate Context with error

an enclosing instance that contains
    org.eclipse.jetty.server.handler.ContextHandler.Context is required

because now it is an inner class and also no such constructor.

Most examples are for jetty 6 and 7. Could you please provide simple example how to start servlet at jetty 8?

like image 711
NullPointer Avatar asked Feb 14 '12 14:02

NullPointer


1 Answers

This is the Jetty 8 equivalent to your code. It's still just as simple as it was before, however the API has changed slightly.

If this isn't working for you, then you probably have a classpath issue - Jetty 8 is separated into a lot of independent jar files, and you will need a number of them. At the very least you need:

  • jetty-continuation
  • jetty-http
  • jetty-io
  • jetty-security
  • jetty-server
  • jetty-servlet
  • jetty-util
  • servlet-api

If you have those jars, then this code should work fine:

package test;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;

public class Jetty8Server {
    public static class MyServlet extends HttpServlet {
        protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
            response.setContentType("text/plain");
            response.getWriter().write(getClass().getName() + " - OK");
        }
    }
    public static void main(String[] args) throws Exception {
        Server server = new Server(8080);
        ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS);
        handler.setContextPath("/"); // technically not required, as "/" is the default
        handler.addServlet(MyServlet.class, "/communication-service");
        server.setHandler(handler);
        server.start();
    }
}
like image 73
Tim Avatar answered Oct 03 '22 07:10

Tim