Migrating from Jetty 6 to Jetty 8

I am using jetty6 in a simple application as a built-in servlet container. I decided to upgrade it to Jetty 8. At Jetty 6 it was pretty easy 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 does not work in Jetty8. Unfortunately, I cannot find a simple example for this version. Unable to create error context

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

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

Most examples are for berths 6 and 7. Could you provide a simple example of how to start a servlet on pier 8?

+8
java servlets jetty
source share
2 answers

This is Jetty 8, equivalent to your code. It is still as simple as before, but the API has changed a bit.

If this does not work for you, you probably have a problem with the classpath - Jetty 8 splits into many independent jar files, and you will need their number. At least you need:

  • Berth-continued
  • Berth client
  • Berth
  • Berth-safety
  • Berth server
  • Berth servlet
  • Berth-Util
  • servlet api

If you have these banks, 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(); } } 
+13
source share

The pier is now part of Eclipse. The documentation here is for Jetty 7, but claims that it should work for Jetty 8. There is an example of using servlets at the end of the page.

+1
source share

All Articles