如何调用REST服务 [英] How to invoke a REST service
问题描述
我创建了一个REST服务,该服务根据提出的请求从数据库中检索数据并以JSON格式返回.
I have created a REST service which retrieves data from the database as per the request made and returns it JSON format.
现在,我需要创建一个带有按钮的HTML页面,单击该按钮应从服务中获取适当的数据.我了解到可以通过ajax完成.但是不知道该怎么做.
Now, I need to create a HTML page with a button that, when clicked, should get the appropriate data from the service. I have learnt that this can be done through ajax. But am not aware how to do it.
该服务使用Spring Framework和Apache CXF,并在重要的情况下从Mysql数据库检索数据.
The service uses Spring Framework and Apache CXF and retrieves data from a Mysql database, if that matters.
我添加的用于创建客户端的代码:
Code i have added to create my client:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.getJSON('http://localhost:8080/CxfRestService/rest/employeeservices/getList');
});
});
});
</script>
</head>
<body>
<input type="button" id="driver" value="Get Employee Data" />
</body>
我是否需要将HTML页面放入Java项目并将相关配置添加到我的web.xml
/beans.xml
之类的东西中?
Do i need to place my HTML page into my Java project and add the related configuration in my web.xml
/beans.xml
or something?
推荐答案
好吧,您所做的所有服务都是响应HTTP请求.因此,您需要发送一个-要么
Well, all your service does is respond to HTTP requests. So, you need to send one - either
- 引导浏览器移动到相应的URL(
document.location.href = <url>
),或者 - 发送
XMLHTTPRequest
(又名AJAX)并解析结果, JQuery具有内置功能.- 然后编辑当前加载的页面,以使用DOM的方式包含结果(请参见例如为此在"jquery教程编辑DOM"上使用Google )
- 例如参见 AJAX简介-W3Schools 了解AJAX概述.它描述了这种情况在普通JS中是如何发生的,
jquery.ajax
是对此的便捷包装.
- direct the browser to move to a corresponding URL (
document.location.href = <url>
), or - send an
XMLHTTPRequest
(aka AJAX) and parse the result, for which JQuery has built-in functionality.- then edit the currently loaded page to include the results the way you like using DOM (see e.g. Google on "jquery tutorial editing DOM" for that)
- See e.g. AJAX Introduction - W3Schools for an AJAX overview. It describes how this happens in plain JS,
jquery.ajax
is a convenient wrapper over that.
您无需以任何方式将客户端内容与Java项目连接-REST专门设计为允许它们独立.
You don't need to connect you client-side stuff with the Java project in any way - REST is specifically designed to allow them to be independent.
这篇关于如何调用REST服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!