Jersey JAX-RS register more controllers on embedded Jetty

Alex Mawashi :

I'm trying to implement a restful web service using Jersey JAX-RS. I embedded a Jetty web server and wanted to register all the controllers on it.

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

in which EntryPoint is the controller:

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

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

and this is registered using 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 can I register many controllers?

If I add other controller classes as params I don't know what key name I must give to each one, because only "jersey.config.server.provider.classnames" seems to work and works once. Thanks.

Paul Samsotha :

Because you can only use the property once, you need to use a comma delimited list as the value classOne, classTwo, classThree.

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

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

See ServerProperties for more properties you can set. Here PROVIDER_PACAKGES is a constant, whose string value is jersey.config.server.provider.packages. Same with the classnames property there is a constant PROVIDER_CLASSNAMES.

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=99799&siteId=1