marți, 6 octombrie 2015

JAX-RS consume a RESTful web service from JSF

JavaEE 7 Client API for JAX-RS API is useful to access the RESTful web services. Basic steps:

  • Get the instance of javax.ws.rs.client.Client class (entry point for invoking RESTful web services).
  • Create an instance of javax.ws.rs.client.WebTarget using the instance of Client class (used to invoke a RESTful web service at some location or URI).
  • Populate the target with the required data (e.g. MIME type, post data, query parameters), and create a request of appropriate HTTP method type which would be an instance of javax.ws.rs.client.Invocation.
  • Obtain the response from the desired RESTful web service via javax.ws.rs.client.Invocation object.

Let's suppose that we have the following JAX-RS resource:

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!";
 }
}

Configured as:

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("webresources")
public class ApplicationConfig extends Application {
}

Supposing that our application is named JaxrsSimpleJSFClient_EE7, our resource is available at:

http://localhost:8080/JaxrsSimpleJSFClient_EE7/webresources/helloworld

From a CDI managed bean we can access this resource like below:

@Named
@ViewScoped
public class ClientBean implements Serializable {

 private final Client jaxrsClient;
 // for simple demo, URL is hard-coded
 private final String jaxrsResource = "http://localhost:8080/JaxrsSimpleJSFClient_EE7/webresources/helloworld/";
   
 private String hello;

 public ClientBean() {
  // get the instance of client which will be entry point to invoking services
  jaxrsClient = ClientBuilder.newClient();
 }

 public void sayHelloWorldAction() {
  // targeting the JAX-RS serivce we want to invoke by capturing it in WebTarget instance
  WebTarget webTarget = jaxrsClient.target(jaxrsResource);

  // build the request (e.g. a GET request)
  Invocation invocation = webTarget.request("text/plain").buildGet();

  // invoke the request
  Response response = invocation.invoke();
       
  // set the response in the bean property
  this.hello = response.readEntity(String.class);
 }

 public String getHello() {
  return hello;
 }

 public void setHello(String hello) {
  this.hello = hello;
 }       
}

A simple JSF page for test:

<h:form>
 <h:commandButton value="JAX-RS Hello World!" action="#{clientBean.sayHelloWorldAction()}"/>
 #{clientBean.hello}
</h:form>

The complete application is available here.

Read also:

Niciun comentariu:

Trimiteți un comentariu