您的位置:首页 > 其它

通过ajax调用WebService服务

2014-02-23 19:49 253 查看
首先创建一个自己的ws:

package cn.wuchuanlong.ws;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.BindingType;
import javax.xml.ws.Endpoint;
/**
* @WebService将java类标记为实现webservice或者将java接口标记为webservice接口,添加此注解后
*      类中的所有非静态方法将会发布暴露出去,如果希望某个非静态、非final方法不发布出去,可以在方法上加上
*      @WebMethod(Exclude=true),如果一个类加上了wenservice注解,则必须要至少一个方法暴露出去,否则
*      启动失败
* EndPoint 发布,静态方法不能暴露出去,不能发布出去
* @author Administrator
*
*/
@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)//解决jdk版本低的问题
public class FirstWebService {
@WebMethod(exclude=true)
public String sayHello1(String name){
return null;
}
public String sayHello(String name){
return "hello "+name;
}
public static void main(String[] args) {
/**
* Endpoint用于将一个已经添加了@WebService注解的类的对象绑定到一个地址的端口上,发布一个服务
* public会启动一个新的线程,底层实现还是socket监听
*
*/
Endpoint.publish("http://localhost:6789/ws", new FirstWebService());
//http://localhost:6789/ws?wsdl
}

}
然后运行这个程序,再编写下面这个html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
</head>
<script type = "text/javascript">
var request;
if(window.ActiveXObject)
{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
request = new XMLHttpRequest();
}
//url
var url = "http://localhost:6789/ws";
//open
request.open("POST",url,true);
//request header
request.setRequestHeader("Content-Type","text/xml;charset=utf-8");
//back
request.onreadystatechange = back;
//send request
var soap = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"                                  xmlns:ns0="http://ws.wuchuanlong.cn/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"                          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><ns0:sayHello><arg0 >ddd</arg0> </ns0:sayHello></soapenv:Body></soapenv:Envelope>';
request.send(soap);
function back()
{
if(request.readyState == 4)
{
if(request.status == 200)
{
alert(request.responseXML);

}
}
};
</script>
<body>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息