1. 程式人生 > >利用JavaScript SOAP Client直接呼叫webService --完整的前後臺配置與呼叫示例

利用JavaScript SOAP Client直接呼叫webService --完整的前後臺配置與呼叫示例

在前端javascript程式碼中直接呼叫webService服務,可以將後臺呼叫webService的業務程式碼轉移到前臺,這樣做的好處是:

1) 減少了後臺編碼量;

2) 在特定的情況下有助於減輕伺服器壓力,節省伺服器資源;

3) 有效提高伺服器端的資源利用率;

但是也存在一定的弊端:

1) 前端javascript編碼的穩定性一直以來備受詬病;

2) 並且對不同瀏覽器的編碼除錯比較麻煩;

對於JavaScript SOAP Client的優缺點暫且不論,現在主要來了解是如何使用這個js庫。

1  java後臺webService釋出

任何前端的資料訪問都離不開離不開後臺webService

的支撐,因此後臺webService類庫的選擇以及配置是很關鍵的,只有在正確的類庫版本和正確的配置webService方可保證後臺對外釋放的介面能夠被有效呼叫。在java語言中有多重webService類庫供大家使用,其中最常用的三種為Axis、Xfire 、Restlet。

現在以axis 1.4 來進行後臺webService介面的配置釋出。

1) 建立一個web工程,在工程的web.xml檔案中新增如下配置資訊:

<servlet>
		<servlet-name>AxisServlet</servlet-name>
		<servlet-class>org.apache.axis.transport.http.AxisServlet</servlet-class>
	</servlet>
	<servlet>
		<servlet-name>AdminServlet</servlet-name>
		<servlet-class>org.apache.axis.transport.http.AdminServlet</servlet-class>
		<load-on-startup>100</load-on-startup>
	</servlet>
	<servlet>
		<servlet-name>SOAPMonitorService</servlet-name>
		<servlet-class>org.apache.axis.monitor.SOAPMonitorService</servlet-class>
		<init-param>
			<param-name>SOAPMonitorPort</param-name>
			<param-value>5001</param-value>
		</init-param>
		<load-on-startup>100</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>AxisServlet</servlet-name>
		<url-pattern>/servlet/AxisServlet</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>AxisServlet</servlet-name>
		<url-pattern>*.jws</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>AxisServlet</servlet-name>
		<url-pattern>/services/*</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>SOAPMonitorService</servlet-name>
		<url-pattern>/SOAPMonitor</url-pattern>
	</servlet-mapping>
	<mime-mapping>
		<extension>wsdl</extension>
		<mime-type>text/xml</mime-type>
	</mime-mapping>
	<mime-mapping>
		<extension>xsd</extension>
		<mime-type>text/xml</mime-type>
	</mime-mapping>

2) 用於釋出服務的server-config.wsdd檔案配置:

<?xml version="1.0" encoding="UTF-8"?>
<deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
	<globalConfiguration>
		<parameter name="adminPassword" value="admin" />
		<parameter name="attachments.implementation" value="org.apache.axis.attachments.AttachmentsImpl" />
		<parameter name="sendXsiTypes" value="true" />
		<parameter name="sendMultiRefs" value="true" />
		<parameter name="sendXMLDeclaration" value="true" />
		<parameter name="axis.sendMinimizedElements" value="true" />
		<requestFlow>
			<handler type="java:org.apache.axis.handlers.JWSHandler">
				<parameter name="scope" value="session" />
			</handler>
			<handler type="java:org.apache.axis.handlers.JWSHandler">
				<parameter name="scope" value="request" />
				<parameter name="extension" value=".jwr" />
			</handler>
		</requestFlow>
	</globalConfiguration>
	<handler name="LocalResponder" type="java:org.apache.axis.transport.local.LocalResponder" />
	<handler name="URLMapper" type="java:org.apache.axis.handlers.http.URLMapper" />
	<handler name="Authenticate" type="java:org.apache.axis.handlers.SimpleAuthenticationHandler" />
	<service name="AdminService" provider="java:MSG">
		<parameter name="allowedMethods" value="AdminService" />
		<parameter name="enableRemoteAdmin" value="false" />
		<parameter name="className" value="org.apache.axis.utils.Admin" />
		<namespace>http://xml.apache.org/axis/wsdd/</namespace>
	</service>
	<service name="Version" provider="java:RPC">
		<parameter name="allowedMethods" value="getVersion" />
		<parameter name="className" value="org.apache.axis.Version" />
	</service>
	
	<!-- xedit 生成表格/表單通用服務 -->
	<service name="XeditService" provider="java:RPC">
		<parameter name="allowedMethods" value="*"/>
		<parameter name="scope" value="Request"/>
		<parameter name="className" value="com.adam.xedit.service.server.XeditService"/>
		<parameter name="wsdlPortType" value="Xedit"/>
		<parameter name="typeMappingVersion" value="1.2"/>
	</service>
	
	<transport name="http">
		<requestFlow>
			<handler type="URLMapper" />
			<handler type="java:org.apache.axis.handlers.http.HTTPAuthHandler" />
		</requestFlow>
	</transport>
	<transport name="local">
		<responseFlow>
			<handler type="LocalResponder" />
		</responseFlow>
	</transport>
	
</deployment>

其中xedit 生成表格/表單通用服務是我們將要提供的介面類。

3) 對外釋放的介面類:

package com.adam.xedit.service.server;

import javax.xml.rpc.ServiceException;

import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.springframework.context.ApplicationContext;
import org.springframework.remoting.jaxrpc.ServletEndpointSupport;

import com.adam.xedit.service.server.biz.XeditServiceBiz;

/**
 * 對外呼叫的介面
 * @公司名稱:
 * @作者:
 * @建立時間:
 */
public class XeditService extends ServletEndpointSupport
{
    private static final long serialVersionUID = 1L;

    private ApplicationContext applicationContext;
    private XeditServiceBiz xsBiz;

    protected void onInit() throws ServiceException
    {
        super.onInit();
        applicationContext = super.getApplicationContext();
        xsBiz = (XeditServiceBiz) applicationContext.getBean("xsBiz");
    }
  
  //略去的程式碼
  
    /**
     * 用於javascript soapClient呼叫介面服務的測試
     * 
     * @param name 名字
     * @return
     */
    public String helloWorld(String name)
    {
        String str = "hello," + name;
        System.out.println(str);
        return str;
    }
  
    public void destroy()
    {
        super.destroy();
    }

    public void invoke(MessageContext arg0) throws AxisFault
    {
        // TODO Auto-generated method stub
    }
}

這個類繼承了import org.springframework.remoting.jaxrpc.ServletEndpointSupport類,很明顯我們是在spring框架下進行開發的,而且這個類中本來還有其他方法,略去。現在只需一個helloWorld() 方法來測試即可。Spring相關的配置也略去。

2 Javascript SOAP Client 前端呼叫webService

1) 頁面helloXeditService.htm

<html>
<head>
<script type="text/javascript" src="../gis/class/jquery-1.2.6.js"></script>
<script type="text/javascript" src="../gis/js.src/xedit.service.js"></script>
<script type="text/javascript" src="../gis/js.src/soapclient21.js"></script>

<!-- 此處略去此理沒用到的js -->
<script language="javascript">
		var serviceUrl = "../../services/XeditService";
		var xeditService = new XeditService(serviceUrl);
	/*
	* 均用於測試helloWorld
	**/
	$(document).ready(function(){
		$('#btnTest').click(function(){
			var txtTest = $('#txtTest').val();
			var result = xeditService.helloWorld(txtTest);
			if(result.error){
				alert(result.errorDetail.string);return false;
			}else{
				$('#txtTest').val(result.value);
				alert(txtTest);
			}
		});
	});
	</script>
</head>
<body>
	<div id="mainDiv" style="width:100%;">
		<!-- propertyGrid  -->
		<div id="propertyGridDiv" style="width:350px;">
			<!-- 測試用 -->
		    <table>
		        <tr id="trTest">
		            <td style="border-color:red;"><input type="text" id="txtTest" width="300px";></input></td>
		            <td align="left"><input type="button" id="btnTest" value="測試" ></input></td>
		        </tr>
		    </table>
  
  ...
  </body>
  </html>

該頁面也刪去了該示例沒用到的程式碼。

1) Xedit.service.js

function XeditService(url){
	this.base = Xedit2ServiceBase;
    this.base(url);
}

XeditService.prototype = new Xedit2ServiceBase;

//helloWorld測試(用於測試JavaScript SOAP Client呼叫service是否成功)
XeditService.prototype.helloWorld = function(name){
	var param = new SOAPClientParameters();
	param.add('name',name);
	var result = SOAPClient.invoke(this._url, "helloWorld", param, false);
	return result;
  }
  //略去不相關的程式碼
function Xedit2ServiceBase(url){
	this._url = url;
}

Xedit2ServiceBase.prototype.toString = function(){
	return this._url;
  }
  //略去不相關的程式碼

1) 頁面測試:

輸入


點選測試彈出框


輸入框回填資料


後臺控制檯列印


以上測試就完成了Javascript SOAP ClientwebService介面的呼叫。免去了mvc中的controller部分並且將部分業務程式碼轉移到了js前端來處理。