Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to consume RESTful web service in my JSF project?

Tags:

java

rest

jsf

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 :)

like image 867
TCM Avatar asked Jun 06 '10 12:06

TCM


People also ask

How do I consume a RESTful web service?

A more useful way to consume a REST web service is programmatically. To help you with that task, Spring provides a convenient template class called RestTemplate . RestTemplate makes interacting with most RESTful services a one-line incantation. And it can even bind that data to custom domain types.

How do you consume a service in Java?

Just make an http request to the required URL with correct query string, or request body. For example you could use java. net. HttpURLConnection and then consume via connection.


1 Answers

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.

like image 66
Behrang Avatar answered Sep 21 '22 03:09

Behrang