微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过ajax调用WebService服务

首先创建一个自己的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>

原文地址:https://www.jb51.cc/ajax/546642.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐