Java – Jersey JAX-RS registers more controllers on embedded jetty

Jersey JAX-RS registers more controllers on embedded jetty… here is a solution to the problem.

Jersey JAX-RS registers more controllers on embedded jetty

I’m trying to implement a Restful web service using Jersey JAX-RS.
I embed a Jetty web server and want to register all controllers on it.

I’m based on this example:
https://nikgrozev.com/2014/10/16/rest-with-embedded-jetty-and-jersey-in-a-single-jar-step-by-step/

where EntryPoint is Controller:

@Path("/entry-point")
public class EntryPoint {

@GET
  @Path("test")
  @Produces(MediaType.TEXT_PLAIN)
  public String test() {
    return "Test";
  }
}

This is registered with the key name “jersey.config.server.provider.classnames” as follows:

public class App {

public static void main(String[] args) throws Exception {
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

Server jettyServer = new Server(8080);
    jettyServer.setHandler(context);

ServletHolder jerseyServlet = context.addServlet(
         org.glassfish.jersey.servlet.ServletContainer.class, "/*");
    jerseyServlet.setInitOrder(0);

 Tells the Jersey Servlet which REST service/class to load.

jerseyServlet.setInitParameter(
       "jersey.config.server.provider.classnames",
       EntryPoint.class.getCanonicalName());

try {
        jettyServer.start();
        jettyServer.join();
    } finally {
        jettyServer.destroy();
    }
  }
}

How do I register multiple Controllers?

If I add other Controller classes as arguments, I don’t know what key name I have to specify for each Controller class, because only “jersey.config.server.provider.classnames” seems to work and work once.
Thank you.

Solution

Because you can only use this property once, you need to use a comma-separated list as the values classOne, classTwo, classThree.

Another option is to use the property jersey.config.server.provider.packages and give it only one package to scan recursively

jerseyServlet.setInitParam(ServerProperties.PROVIDER_PACKAGES, "my.package.to.scan");

See also ServerProperties You can set more properties. The PROVIDER_PACAKGES here is a constant whose string value is jersey.config.server.provider.packages. As with the classnames attribute, there is a constant PROVIDER_CLASSNAMES.

By declaring a package to scan, Jersey scans the package recursively (by default) and registers all annotated @Path and @Provider the classes it finds in the scan.

Related Problems and Solutions