1. 程式人生 > >webservice學習筆記(十二):js與jquery利用ajax獲取webservice返回值

webservice學習筆記(十二):js與jquery利用ajax獲取webservice返回值

1.webservice服務端程式碼如圖(ps:只是一個簡單的sayHello的demo):

 

-服務端是基於spring的,具體beans.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd">
    <jaxws:endpoint id="nameBegin" implementor="com.wayne.ws.HelloWsImpl"
        

address="/gotham">
        <!-- 配置日誌入攔截器 -->
        <jaxws:inInterceptors>
        <bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
        </jaxws:inInterceptors>
        <!-- 配置日誌出攔截器 -->
        <jaxws:outInterceptors>
        <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
        </jaxws:outInterceptors>
    </jaxws:endpoint>
</beans>

-web.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>day_fif_ws_cxf_spring_web_se</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 配置beans.xml檔案 -->
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <!-- src下面檔案引數為classpath -->
  <param-value>classpath:beans.xml</param-value>
  </context-param>
  <!-- 應用啟動的監聽器 -->
  <listener>
  <listener-class>
  org.springframework.web.context.ContextLoaderListener
  </listener-class>
  </listener>
  <!-- gotham的所有請求都會先經過cxf框架 -->
  <servlet>
  <servlet-name>CXFServlet</servlet-name>
  <servlet-class>
  org.apache.cxf.transport.servlet.CXFServlet
  </servlet-class>
  <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  <servlet-name>CXFServlet</servlet-name>
  <url-pattern>

/gotham/*</url-pattern>
  </servlet-mapping>
</web-app>

-接下來我們部署到tomcat中執行,並用瀏覽器開啟我們的wsdl文件:

-這裡要注意我們的url是兩個gotham,個人理解是因為我的beans.xml的endpoint的address屬性和web.xml的過濾都加上了gotham,所以訪問需要gotham,因為web.xml全部都過濾就不會訪問到jsp頁面,雖然這裡的服務端也不需要訪問jsp頁面,如果全部請求經過cxf框架,我們去訪問jsp頁面會顯示如下:

-接下來我們用eclipse內建的web service explorer訪問url,並使用sayHello(),由於在服務端配置的入攔截器,所以我們可以獲取到客戶端的請求報文:

 

這裡我們需要把報文(PayLoad後的內容)暫時儲存起來,可以注意到<arg0></arg0>中間是我們輸入的值,

所以後面的ajax請求我們要進行拼接,把輸入框中的內容放到<arg0></arg0>標籤裡去,並把拼接好的內容傳送到我們的伺服器的url,

然後再利用回撥函式獲取伺服器的響應內容,這就是大致實現思路

-接下來就是利用cxf的命令進行生成客戶端程式碼(詳細操作請參考前面的內容):

-這裡我們依然是基於spring的,client-beans.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd">
    <!-- id屬性為唯一標識,serviceClass屬性為根據服務端SEI生成的全類名, 
    address屬性為服務端的地址(去掉?wsdl即可) -->
    <jaxws:client id="nameClient" serviceClass="com.wayne.ws.HelloWs"
        address="http://localhost:8080/day_six_ws_cxf_spring_web_ajax/gotham/gotham">
        <jaxws:outInterceptors>
        <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
        </jaxws:outInterceptors>
    </jaxws:client>
</beans>

-客戶端jsp程式碼如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function(){
    $("#startJq").click(function(){
        var name=document.getElementById("userName").value;
        alert(name);
        var data='<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://ws.wayne.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><q0:sayHello><arg0>'+name+'</arg0></q0:sayHello></soapenv:Body></soapenv:Envelope>';
        $.ajax({
            type:"post",
            url:"http://localhost:8080/day_six_ws_cxf_spring_web_ajax/gotham/gotham",
            data:data,
            dataType:"xml",
            success:function(msg){
            alert("success");
            var $result=$(msg);
            var value=$result.find("return").text();
            alert(value);
            },
            error:function(){
                alert("錯誤");
            }
        });
    });
});
function reqWebService(){
    var name=document.getElementById("userName").value;
    var data='<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://ws.wayne.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><q0:sayHello><arg0>'+name+'</arg0></q0:sayHello></soapenv:Body></soapenv:Envelope>';
    var request=getRequest();
    request.onreadystatechange=function(){
        if(request.readyState==4 && request.status==200){
            var result=request.responseXML;
            alert(result);
            var returnEle=result.getElementsByTagName("return")[0];
            var value=returnEle.firstChild.data;
            alert(value);
        }
    };
    request.open("POST","http://localhost:8080/day_six_ws_cxf_spring_web_ajax/gotham/gotham");
    request.setRequestHeader("Content-type","");
    request.send(data);
}
function getRequest(){
    var xmlHttp=null;
    try{
        //firefox safari chrome
        xmlHttp=new XMLHttpRequest();
    }catch(e){
        //IE
        try{
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }catch(e){
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}
</script>
<body>
使用者名稱:<input id="userName" name="userName"/>
<button onclick="reqWebService()">ajax請求webservice</button>
<button id="startJq">jquery請求webservice</button>
</body>
</html>

-使用jquery的ajax注意儘量不要寫ip,因為可能會導致無響應,寫localhost即可,測試結果如下: