使用JQuery、Ajax來呼叫WebService服務
阿新 • • 發佈:2020-11-28
基於Spring + CXF框架的Web Service
1、在之前的基礎上修改的,如果想使用JQuery、Ajax來呼叫WebService服務,必須需要先獲取到請求的引數值,我的引數值是下面的這部分,如何獲取到這引數值呢,只需要在客戶端配置出攔截器即可,後臺列印的引數,然後配置到自己需要的地方即可。
1 <soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Header><zhangsansan><name>張姍姍</name><password>123456</password></zhangsansan></soap:Header><soap:Body><ns2:getOrderById xmlns:ns2='http://ws.webservice.bie.com/'><arg0>1</arg0></ns2:getOrderById></soap:Body></soap:Envelope>
下面配置伺服器端的beans.xml配置,這裡還是使用賬號密碼驗證服務,新增了出攔截器配置,其他還是使用上篇的類和配置。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:jaxws="http://cxf.apache.org/jaxws" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd7 http://cxf.apache.org/jaxws http://cxf.apache.org/jaxws"> 8 9 <!-- 引cxf-2.5.9.jar此包下面的配置,這些配置不在此專案中,cxf的一些核心配置 --> 10 <import resource="classpath:META-INF/cxf/cxf.xml" /> 11 <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /> 12 <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> 13 14 <!-- 15 jaxws:endpoint標籤配置終端。 16 implementor是實現類。 17 address是虛擬地址。 18 --> 19 <jaxws:endpoint id="orderWS" 20 implementor="com.bie.webservice.ws.impl.OrderWSImpl" 21 address="/orderws"> 22 <!-- 伺服器端配置入攔截器 --> 23 <jaxws:inInterceptors> 24 <!-- 配置自定義的攔截器,注入到ioc容器中 --> 25 <bean class="com.bie.webservice.interceptor.CheckUserInterceptor"></bean> 26 </jaxws:inInterceptors> 27 <!-- 伺服器端日誌出攔截器 --> 28 <jaxws:outInterceptors> 29 <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" /> 30 </jaxws:outInterceptors> 31 </jaxws:endpoint> 32 33 </beans>
下面配置客戶端的client-beans.xml配置,這裡還是使用賬號密碼驗證服務,新增了入攔截器配置,其他還是使用上篇的類和配置。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:jaxws="http://cxf.apache.org/jaxws" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://cxf.apache.org/jaxws http://cxf.apache.org/jaxws"> 8 9 <!-- 10 客戶端配置: 11 serviceClass根據此類動態產生介面的代理物件。 12 address是指的是webservice請求的地址。 13 --> 14 <jaxws:client id="orderClient" 15 serviceClass="com.bie.webservice.ws.OrderWS" 16 address="http://localhost:8080/webServiceCxf_Spring/orderws"> 17 18 <!-- 客戶端配置出攔截器類 --> 19 <jaxws:outInterceptors> 20 <!-- 客戶端出攔截器 --> 21 <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" /> 22 <bean 23 class="com.bie.webservice.ws.interceptor.ClientValidateUserInterceptor"> 24 <!-- 通過構造引數傳遞給客戶端攔截器類 --> 25 <constructor-arg name="name" value="張姍姍" /> 26 <constructor-arg name="password" value="123456" /> 27 </bean> 28 </jaxws:outInterceptors> 29 <!-- 客戶端入攔截器 --> 30 <jaxws:inInterceptors> 31 <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" /> 32 </jaxws:inInterceptors> 33 </jaxws:client> 34 35 </beans>
2、然後搞一個index.jsp類,引用jquery,bootstrap樣式這些東西,如下所示:
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 7 <title>搞什麼???</title> 8 <link rel="stylesheet" href="bootstrap.min.css"> 9 10 <script src="jquery-1.7.2.js"></script> 11 <script src="bootstrap.min.js"></script> 12 13 <script type="text/javascript"> 14 15 $(function(){ 16 17 // HttpURLConnection請求webservice 18 $("#btn2").click(function(){ 19 var name = document.getElementById("name").value; 20 var password = document.getElementById("password").value; 21 $.post( 22 "HttpURLConnectionServlet", 23 { 24 "name":name, 25 "password":password 26 }, 27 function(msg) { 28 // console.log(msg); 29 var $Result = $(msg); 30 var value = $Result.find("return").text(); 31 console.log(value); 32 }, 33 "xml" 34 ); 35 }); 36 37 // Jquery請求webservice 38 $("#btn").click(function(){ //回撥函式 39 var name = document.getElementById("name").value; 40 var password = document.getElementById("password").value; 41 // var data = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:sayHello xmlns:ns2="http://sei.webservice.bie.com/"><arg0>'+name+'</arg0></ns2:sayHello></soap:Body></soap:Envelope>'; 42 var data = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><zhangsansan><name>'+name+'</name><password>'+password+'</password></zhangsansan></soap:Header><soap:Body><ns2:getOrderById xmlns:ns2="http://ws.webservice.bie.com/"><arg0>1</arg0></ns2:getOrderById></soap:Body></soap:Envelope>'; 43 console.log(data); 44 $.ajax({ 45 type : "post", 46 url : "http://localhost:8080/webServiceCxf_Spring/orderws", 47 data : data, 48 success : function(msg){ 49 console.log("------"); 50 var $Result = $(msg); 51 var value = $Result.find("return").text(); 52 console.log(value); 53 }, 54 error : function(msg) { 55 console.log("-----" + msg); 56 }, 57 dataType : "xml" 58 }); 59 }); 60 }); 61 62 63 // AJax請求webservice 64 function reqWebService() { 65 // 獲取到name屬性的值 66 var name = document.getElementById("name").value; 67 var password = document.getElementById("password").value; 68 // 並將傳遞的name屬性值拼接到該data字串中 69 // var data = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:sayHello xmlns:ns2="http://sei.webservice.bie.com/"><arg0>'+name+'</arg0></ns2:sayHello></soap:Body></soap:Envelope>'; 70 var data = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><zhangsansan><name>'+name+'</name><password>'+password+'</password></zhangsansan></soap:Header><soap:Body><ns2:getOrderById xmlns:ns2="http://ws.webservice.bie.com/"><arg0>1</arg0></ns2:getOrderById></soap:Body></soap:Envelope>'; 71 // 建立XMLHttpRequest物件 72 var request = getRequest(); 73 // 響應返回的資料,設定回撥函式 74 request.onreadystatechange = function(){ 75 if(request.readyState==4 && request.status==200) { 76 var result = request.responseXML; 77 console.log(result.all[0]); 78 result = result.all[0] 79 var returnEle = result.getElementsByTagName("return")[0]; 80 console.log(returnEle); 81 82 var firstNodeName = returnEle.firstChild.nodeName; 83 console.log(firstNodeName); 84 var firstNodeNameVlaue = returnEle.firstChild.innerHTML; 85 console.log(firstNodeNameVlaue); 86 87 var secondNodeName = returnEle.firstChild.nextElementSibling.nodeName; 88 console.log(secondNodeName); 89 var secondNodeVlaue = returnEle.firstChild.nextElementSibling.innerHTML; 90 console.log(secondNodeVlaue); 91 92 var thirdNodeName = returnEle.firstChild.nextElementSibling.nextElementSibling.nodeName; 93 console.log(thirdNodeName); 94 var thirdNodeVlaue = returnEle.firstChild.nextElementSibling.nextElementSibling.innerHTML; 95 console.log(thirdNodeVlaue); 96 } 97 }; 98 99 // 請求地址,開啟連線 100 request.open("POST", "http://localhost:8080/webServiceCxf_Spring/orderws"); 101 // 如果是POST請求,要包含一個請求頭,設定字符集編碼,不然後臺獲取到的是亂碼的,設定一個請求頭 102 request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); 103 // 傳送請求體,傳送請求,將data作為請求體傳送過去 104 request.send(data); 105 } 106 107 // XMLHttpRequest物件,使用各個瀏覽器之間的操作 108 function getRequest() { 109 var xmlHttp = null; 110 try { 111 // Firefox, Opera 8.0+, Safari chrome 112 xmlHttp = new XMLHttpRequest(); 113 } catch (e) { 114 // Internet Explorer 115 try { 116 xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); 117 } catch (e) { 118 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 119 } 120 } 121 return xmlHttp; 122 } 123 </script> 124 </head> 125 <body> 126 127 128 129 <center> 130 131 <h1></h1> 132 <div class="row"> 133 <div class="col-md-3"></div> 134 <div class="col-md-3"> 135 賬號:<input type="text" class="form-control" id="name" name="name" value="" /> <br/> 136 </div> 137 <div class="col-md-3"> 138 密碼:<input type="text" class="form-control" id="password" name="password" value="" /> 139 </div> 140 <div class="col-md-3"></div> 141 </div> 142 143 <br><br/> 144 <button onclick="reqWebService()" class="btn btn-primary">AJax請求webservice</button> 145 <button id="btn" class="btn btn-success">Jquery請求webservice</button> 146 <button id="btn2" class="btn btn-danger">HttpURLConnection請求webservice</button> 147 </center> 148 </body> 149 </html>
這裡使用了三種方式,分別是AJax請求webservice、Jquery請求webservice、HttpURLConnection請求webservice,所以搞一個HttpURLConnection的servlet來接收請求,如下所示:
1 package com.bie.webservice.ws.servlet; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.OutputStream; 6 import java.net.HttpURLConnection; 7 import java.net.URL; 8 9 import javax.servlet.ServletException; 10 import javax.servlet.ServletOutputStream; 11 import javax.servlet.http.HttpServlet; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 15 /** 16 * 17 * @author 18 * 19 */ 20 public class HttpURLConnectionServlet extends HttpServlet { 21 22 private static final long serialVersionUID = 1L; 23 24 protected void doPost(HttpServletRequest request, HttpServletResponse response) 25 throws ServletException, IOException { 26 // 獲取到賬號密碼的值 27 String name = request.getParameter("name"); 28 String password = request.getParameter("password"); 29 System.out.println("doPost " + name + ", " + password); 30 31 // String data = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" 32 // + "<soap:Body><ns2:sayHello xmlns:ns2='http://sei.webservice.bie.com/'><arg0>" + name 33 // + "</arg0></ns2:sayHello></soap:Body></soap:Envelope>"; 34 35 // 組織資料,將資料拼接一下 36 String data = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" 37 + "<soap:Header><zhangsansan><name>" + name + "</name><password>" + password + "</password>" 38 + "</zhangsansan></soap:Header><soap:Body>" 39 + "<ns2:getOrderById xmlns:ns2='http://ws.webservice.bie.com/'>" 40 + "<arg0>1</arg0></ns2:getOrderById></soap:Body></soap:Envelope>"; 41 42 // 第一步:建立服務地址,不是WSDL地址 43 URL url = new URL("http://localhost:8080/webServiceCxf_Spring/orderws"); 44 45 // 第二步:開啟一個通向服務地址的連線 46 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 47 48 // 第三步:設定引數 49 // 傳送方式設定:POST必須大寫 50 connection.setRequestMethod("POST"); 51 // 設定輸入輸出,因為預設新建立的connection沒有讀寫許可權 52 connection.setDoOutput(true); 53 connection.setDoInput(true); 54 // 設定資料格式:content-type 55 connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); 56 57 // 第四步:組織SOAP資料,傳送請求 58 OutputStream os = connection.getOutputStream(); 59 os.write(data.getBytes("utf-8")); 60 61 // 第五步:接收服務端響應,列印 62 int responseCode = connection.getResponseCode(); 63 // 表示服務端響應成功 64 if (responseCode == 200) { 65 // String xml 66 InputStream is = connection.getInputStream(); 67 System.out.println("return " + is.available()); 68 // 將位元組流轉換為字元流 69 response.setContentType("text/xml;charset=utf-8"); 70 ServletOutputStream outputStream = response.getOutputStream(); 71 72 byte[] buffer = new byte[1024]; 73 int len = 0; 74 while ((len = is.read(buffer)) > 0) { 75 outputStream.write(buffer, 0, len); 76 } 77 outputStream.flush(); 78 } 79 } 80 81 }
需要注意的是,客戶端需要在web.xml配置一下請求地址和轉發的類,或者搞一個Servlet註解也可以,如下所示:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 6 id="WebApp_ID" version="2.5"> 7 <display-name>webServiceCxf_Spring_Client</display-name> 8 <welcome-file-list> 9 <welcome-file>index.html</welcome-file> 10 <welcome-file>index.jsp</welcome-file> 11 </welcome-file-list> 12 13 <servlet> 14 <description></description> 15 <display-name>HttpURLConnectionServlet</display-name> 16 <servlet-name>HttpURLConnectionServlet</servlet-name> 17 <servlet-class>com.bie.webservice.ws.servlet.HttpURLConnectionServlet</servlet-class> 18 </servlet> 19 <servlet-mapping> 20 <servlet-name>HttpURLConnectionServlet</servlet-name> 21 <url-pattern>/HttpURLConnectionServlet</url-pattern> 22 </servlet-mapping> 23 24 25 </web-app>
演示效果,如下所示: