通過soap利用ajax調用WebService主要是爲了解決不同的平臺之間的服務通訊或者數據交換,但是如果在不同的域環境中,每次調用的時候會彈出警告框,要想不每次都彈出警告框,只能手動設置瀏覽器選項,在項目發佈後,去爲每個用戶設置一下會很麻煩。還有就是有時候會出現圖片所顯示XMLHttpRequest的Access-Control-Allow-Origin問題。所以,解決方法就是通過json的傳送數據來代替soap消息的傳送。這有點類似於調用網上的web服務接口然後返回json消息,如查詢天氣。本文使用servlet和jsonp方式模擬soap
(soap調用webservice代碼如下,僅供對比
<html> <head> <!--<meta http-equiv="Access-Control-Allow-Origin" content="*">--> <title>通過ajax調用WebService服務</title> <script> var xhr = new XMLHttpRequest(); function sendMsg(){ // alert("sasdasd") var name = document.getElementById('name').value; //服務的地址 var wsUrl = 'http://localhost:9000/HelloWorld'; // var wsUrl= "http://example/HelloWorldService"; var soap = '<?xml version="1.0" encoding="utf-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://example/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' + " <soapenv:Body><q0:sayHelloWorldFrom><arg0>"+name+"</arg0></q0:sayHelloWorldFrom></soapenv:Body></soapenv:Envelope>"; alert(soap) //打開連接 xhr.open('POST',wsUrl,true); //重新設置請求頭 xhr.setRequestHeader("Content-Type","text/xml;charset=UTF-8"); //設置回調函數 // xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded") // xhr.setRequestHeader("Content-type", "Access-Control-Allow-Origin: POST") xhr.onreadystatechange = _back; //發送請求 xhr.send(soap); } function _back(){ if(xhr.readyState == 4){ alert(xhr.status) if(xhr.status == 200){ alert('調用Webservice成功了'); var ret = xhr.responseXML; var msg = ret.getElementsByTagName('return')[0]; document.getElementById('showInfo').innerHTML = msg.text; //alert(msg.text); } } } </script> </head> <body> <input type="button" value="發送SOAP請求" οnclick="sendMsg();"> <input type="text" id="name"> <div id="showInfo"> </div> </body> </html>
)
由於整個過程不需要webservice了,所以就不需要再編寫webservice的方法,只需要普通的方法就可以實現不同平臺的數據的傳輸。
首先,在idea14.04中利用servlet來模擬原先的soap地址的訪問。新建一個web項目
然後新建一個servlet用來模擬soap訪問url。代碼如下:
import net.sf.json.JSONObject; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; /** * Created by tengqingya-njupt on 2015/8/26. */ public class Servlet extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { doGet(request,response); } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { response.setContentType("text/plain"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); // Map<String, int[]> map = new HashMap<String, int[]>(); Map<String, String> map = new HashMap<String, String>(); PrintWriter out = response.getWriter(); map.put("result", request.getParameter("name")); // int a[]={1,2,3}; //這裏可以在接受到客戶端傳過來的參數result後,調用服務器端的業務代碼,然後把數據封裝到map中,再封裝到json中 map.put("Class","Main"); //將結果組裝成json JSONObject resultJSON = JSONObject.fromObject(map); String jsonpCallback = request.getParameter("jsonpCallback");//客戶端請求參數 out.println(jsonpCallback+"("+resultJSON.toString(1,1)+")");//返回jsonp格式數據 out.flush(); out.close(); } }別忘了配置servlet映射關係:
在web.xml中:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>Servlet</servlet-name> <servlet-class>Servlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet</servlet-name> <url-pattern>/tqy</url-pattern> </servlet-mapping> </web-app>
以上配置說明通過http://localhost:8080/tqy地址就可以訪問我們寫的Servlet代碼了。
啓動tomcat服務器(如果第一次使用idea或者之間沒有配置過tomcat可以按照下圖配置:在文件->設置(setting)->輸入server->加號,add一個服務器)。然後就是啓動,可以在index.jsp文件上右擊鼠標run,然後在瀏覽器中輸入http://localhost:8080/tqy。效果如下:
。這樣服務器端的“webservice”就開發好了。下面開始客戶端網頁的開發。
使用idea新建一個static web項目。再新建一個html文件名爲test。代碼如下:
<!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> <script type="text/javascript" src="jquery.js"></script> </head> <script type="text/javascript"> $(function(){ $.ajax({ type : "get", async:false, url : "http://192.168.11.113:8080/tqy?name='tqy'",//傳參到服務器模擬WS方法傳參 dataType : "jsonp",//數據類型爲jsonp jsonp: "jsonpCallback",//服務端用於接收callback調用的function名的參數 success : function(data){ $("#showcontent").text("Result:"+data.Class) }, error:function(){ alert('fail'); } }); }); </script> <body> <div id="showcontent">Result:</div> </body> </html>以上代碼中data裏面存放的就是json格式的數據,比如之前Class裏面放的是Main,那麼data.Class的值就是Main。效果圖如下: 如果修改data.Class爲data.result.結果如下。
到此。模擬soap調用webservice的過程就大功告成。這樣,原先通過soap調用webservice返回的數據,就可以用servlet返回json數據代替實現了。也是跨平臺調用。