TCM TCM - 1 month ago 74
reST (reStructuredText) Question

How to consume RESTful web service in my JSF project?

As RESTful web services are url based aren't objects, we can't call methods on them. I have a simple web service with only one method in it with is

@GET
. I saw one screencast and it used some javascript library to consume the web service. But, how do I use it with my JSF project? I can't even inject it like a normal web service. Please help. I am new to REST. Can't I consume it in my managed bean?

If the only way to consume the webservice is through javascript, can anybody here give me details of how to consume it through JQuery?

Thanks in advance :)

Answer

You can consume it in your managed bean with no problem. RESTful Web Services usually return JSON or XML formatted objects. You can call the restful web service and depending on the format of its response, parse it either using an XML parser or a JSON parser, or even better use a mapper to map the response to a Java object and use it elsewhere in your application.

Java-JSON mapping libraries are discussed here (screen capture here).

You can use JAXB for XML-Java mapping: https://jaxb.dev.java.net/tutorial/

An XML mapper, maps an XML document to a Java object.

For example, if the response from the Web Service you are using is:

<SampleResponse>
<firstName>James</firstName>
<lastName>Gosling</lastName>
</SampleResponse>

An XML mapper can convert that to an instance of the following class:

public class SampleResponse {
private String firstName;
private String lastName;
// setters and getters
}

In a way like this:

SampleResponse myResponseObj = mapper.fromXML(xmlRespnse);

JSON mappers work in a similar manner.