java 如何在我的 JSF 项目中使用 RESTful Web 服务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2984106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to consume RESTful web service in my JSF project?
提问by TCM
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?
由于 RESTful Web 服务是基于 url 的不是对象,因此我们不能对它们调用方法。我有一个简单的 Web 服务,其中只有一种方法是@GET. 我看到了一个截屏视频,它使用了一些 javascript 库来使用 Web 服务。但是,我如何在我的 JSF 项目中使用它?我什至不能像普通的网络服务一样注入它。请帮忙。我是 REST 的新手。我不能在我的托管 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?
如果使用 webservice 的唯一方法是通过 javascript,这里有人能告诉我如何通过 JQuery 使用它的详细信息吗?
Thanks in advance :)
提前致谢 :)
回答by Behrang Saeedzadeh
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.
您可以毫无问题地在托管 bean 中使用它。RESTful Web 服务通常返回 JSON 或 XML 格式的对象。您可以调用 restful Web 服务,并根据其响应的格式,使用 XML 解析器或 JSON 解析器对其进行解析,或者甚至更好地使用映射器将响应映射到 Java 对象并在应用程序的其他地方使用它。
Java-JSON mapping libraries are discussed here(screen capture here).
You can use JAXB for XML-Java mapping: https://jaxb.dev.java.net/tutorial/
您可以使用 JAXB 进行 XML-Java 映射:https: //jaxb.dev.java.net/tutorial/
An XML mapper, maps an XML document to a Java object.
XML 映射器将 XML 文档映射到 Java 对象。
For example, if the response from the Web Service you are using is:
例如,如果您使用的 Web 服务的响应是:
<SampleResponse>
<firstName>James</firstName>
<lastName>Gosling</lastName>
</SampleResponse>
An XML mapper can convert that to an instance of the following class:
XML 映射器可以将其转换为以下类的实例:
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.
JSON 映射器以类似的方式工作。

