- Thu 22 March 2018
- Tech
Utalizing JAX-RS, Jetty, and Jersey it's possible to create a lightweight RESTful server in no time.
This code produces a standalone JAR file.
Github repo of the full working sourcecode can be found here.
static Server startServer() throws IOException {
// Construct a Jetty Server
final Server server = new Server(new InetSocketAddress("127.0.0.1", 8080));
// Jetty Context Handler
ServletContextHandler handler = new ServletContextHandler();
// Jetty ServletHolder contain a Jersey ServletContainer containing our JAX-RS Application.
ServletHolder helloWorldServlet = new ServletHolder(new ServletContainer(new JaxRsApp()));
// Adding the Servlet to the Context Handler
handler.addServlet(helloWorldServlet, "/app1/*");
// Adding the Context Handler to the Jetty Server
server.setHandler(handler);
// start the server
try {
server.start();
server.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
return server;
}
@ApplicationPath("/")
public class JaxRsApp extends Application {
private final Set<Class<?>> classes;
public JaxRsApp() {
HashSet<Class<?>> c = new HashSet<Class<?>>();
c.add(HelloWorld.class);
classes = Collections.unmodifiableSet(c);
}
@Override
public Set<Class<?>> getClasses() {
return classes;
}
}
@Path("/")
public class HelloWorld {
@GET
@Path("helloworld")
@Produces(MediaType.TEXT_PLAIN)
public String helloworld() {
return "Hello World!";
}
}