In this tutorial we create a minimalistic web application by using JAX-RS annotations. Our provider class contains some simple methods, responding to HTTP GET requests:
@Path("/welcomes") public class Resource { @GET @Path("hello") public String hello() { return "Hi from REST!"; } @GET @Path("short/{name}") public String shortWelcome(@PathParam("name") String name) { return "Hi, " + name; } }
To hold the Web Service configurations we need to create a class which extends javax.ws.rs.core.Application:
package com.mycompany.restdemo; import javax.ws.rs.core.Application; public class ApplicationConfig extends Application { }
To map the incoming requests under this application, annotate the class with @javax.ws.rs.ApplicationPath. Finally by overriding the
public Set<Class<?>> getClasses()
method of the javax.ws.rs.core.Application class return the provider class(es). This will make the methods of the provider class visible under rest/welcomes/hello and rest/welcomes/short/name URLs.
package com.mycompany.restdemo; import java.util.Set; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; @ApplicationPath("/rest") public class ApplicationConfig extends Application { @Override public Set<Class<?>> getClasses() { return getRestResourceClasses(); } private Set<Class<?>> getRestResourceClasses() { Set<Class<?>> resources = new java.util.HashSet<Class<?>>(); resources.add(com.mycompany.restdemo.Resource.class); return resources; } }
Your Web Service is done!
Here is the archive containing this demo project tested in GlassFish 3.1.2. It’s a maven project and you can run it right after extracting (you will need Maven) by executing:
mvn install
in the same folder where the pom.xml file is. This will download the required libraries and deploy the web application under http://localhost:8080/restDemo
restDemo.tar.gz (1.59 KB)