Twitter

joi, 1 octombrie 2015

JAX-RS HelloWorld example

In this post, you can see a very simple JAX-RS application (the HelloWorld example).

This application consist in a Java web application that contain a RESTful root resource class and a class for configuring our application - defines the base URI from which our application's resources respond to requests.

The below POJO class uses the JAX-RS annotations to become a RESTful root resource class:
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("helloworld")
public class HelloWorldResource {

 @GET
 @Produces("text/plain") // default: */*
 public String helloWorld() {
  return "Hello, World!";
 }
}
We can put this in words as follows: This ia a RESTful root resource class hosted at the relative URI, helloworld (you can use /helloworld also, it makes no difference), indicated via @Path annotation. It will respond to requests of type HTTP GET (@GET) and it can produce (return) plain text as the MIME type (text/plain) indicates via the @Produces annotation.

So, the helloworld is the relative URI. Further we need to define the base URI which can be accomplished easily by using the @ApplicationPath annotation in a subclass of javax.ws.rs.core.Application packaged within the WAR:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("webresources")
public class ApplicationConfig extends Application {
}
Done! The application is ready and we can test it by accessing the correct URL in the browser address bar:

http://localhost:8080/JaxrsHelloWorld_EE7/webresources/helloworld

It will simply display: Hello, World!

The complete application is available here.

Niciun comentariu:

Trimiteți un comentariu