现在我们通过Ajax去调用此服务
WebService服务代码如下:
运行启动服务
package cn.itcast.ws; import javax.jws.WebService; import javax.xml.ws.Endpoint; /* * 将 Java 类标记为实现 Web Service,或者将 Java 接口标记为定义 Web Service 接口。 */ @WebService public class HelloService { //此方法不能为static和final类型的 public String sayHrllo(String name) { return "hello" + name; } public static void main(String[] args) { /* * EndPoint--端点服务类,它的方法publish用于将一个已经添加了@WebService注解的对象 * 绑定到一个地址端口上,此方法会启动一个新的线程去监听客户端操作 * * 参数1:服务的发布地址 * 参数2:服务的实现者 * */ Endpoint.publish("http://localhost:6767/hello",new HelloService()); } }
运行启动服务
获取Ajax请求中的请求体:
在Eclipse工具栏中单击Launch the Web Service Explorer(若无此按钮,则依次单击window——>perspective——>Customize Perspective,
在Eclipse工具栏中单击Launch the Web Service Explorer(若无此按钮,则依次单击window——>perspective——>Customize Perspective,
然后在弹出窗口中选择Launch the Web Service Explorer并确定),然后在新页面中的右上角选择WSDL Page按钮,
再单击左侧的WSDL Main出现如下页面(若无反应,则再次点击WSDL page按钮则会成功。。bug???):
在位置3处输入地址http://localhost:6767/hello?wsdl并单击4按钮go, 出现新页面中左侧依次点开找到最底层的方法sayHello方法单击
在位置3处输入地址http://localhost:6767/hello?wsdl并单击4按钮go, 出现新页面中左侧依次点开找到最底层的方法sayHello方法单击
(若无反应,则再次点击WSDL page按钮则会成功。。bug???),出现如下所示页面:
依次执行图示步骤操作后,并找到最下面的status窗口栏双击,出现如下页面:
然后点击右上角的source出现Ajax和WebService的xml数据请求页面:
很奇怪,为啥没有出现基于soap协议的xml格式的请求和响应数据???
————>>空白处单击鼠标右键,选择查看源,然后xml数据就出来了。
依次执行图示步骤操作后,并找到最下面的status窗口栏双击,出现如下页面:
然后点击右上角的source出现Ajax和WebService的xml数据请求页面:
很奇怪,为啥没有出现基于soap协议的xml格式的请求和响应数据???
————>>空白处单击鼠标右键,选择查看源,然后xml数据就出来了。
<html> <head> <title>通过ajax调用WebService服务</title> <script> var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHttp"); } function sendMsg() { var name = document.getElementById("name"); //服务的地址 var wsUrl = 'http://localhost:6767/hello'; //请求体 var soap = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" ' + 'xmlns:q0="http://ws.itcast.cn/" ' + 'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' + '<soapenv:Body>' + '<q0:sayHrllo>' + '<arg0>' + name + '</arg0>' + '</q0:sayHrllo>' + '</soapenv:Body>' + '</soapenv:Envelope>'; //打开链接 xhr.open('POST',wsUrl,true); //重新设置请求头 xhr.setRequestHeader("Content-Type","text/xml;charset=UTF-8"); //设置回掉函数 xhr.onreadystatechange = _back; //发送请求 xhr.send(soap); } function _back(){ if (xhr.readyState == 4) { if (xhr.status == 200) { //alert("调用WebService成功了"); var ret = xhr.responseXML; var msg = ret.getElementsByTagName('return')[0]; document.getElementById("showInfo").innerHTML = msg.textContent; //alert(msg.text); } } } </script> </head> <body> <input type="button" value="发送soap请求" onclick="sendMsg();"/> <input type="text" id="name"/> <div id="showInfo"></div> </body> </html>