Embedding Jetty Server with Jersey as RESTful container with CORS

I came across a scenario where I had to expose a Java SDK based server configuration as RESTFul service. I chose the jetty as embedded http server and jersey as RESTful container. After Googling a while I came across this link which nicely explains how to embed a jetty server in a java programme.

However I also wanted this service available to other web application using CORS. So I wanted to enable jettty CORS filter for the same. After Googling again for a while I came across this link.

Merging idea from above two links finally made a working version of embedded jettey with Jersey supporting CORS.

ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath(“/”); 
Server jettyServer = new Server(Integer.parseInt(9998));
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet( org.glassfish.jersey.servlet.ServletContainer.class, “/*”);
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter( “jersey.config.server.provider.classnames”,
MyServerConfig.class.getCanonicalName());
FilterHolder filterHolder = context.addFilter(org.eclipse.jetty.servlets.CrossOriginFilter
.class, “/*”, EnumSet.of(DispatcherType.REQUEST));
filterHolder.setInitParameter(“allowedOrigins”, “*”);
try { 
jettyServer.start(); jettyServer.join();
} catch (Exception e) {
LOGGER.error(“Error running ServerConfig service”, e);
} finally {
jettyServer.destroy();
}

Here “MyServerConfig.class” is resource class implementing RESTFul service.

One can now access http://localhost:9998/

Like what you read? Give Arun Y a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.