使用分布式编程,很方便不同编程语言之间互相访问,但也必须注意一些技术细节,实现起来才能畅通无阻,取得事半功倍的效果。
首先,创建一个WCF。使用原有网站或新建一个网站,并将端口动态改为固定,如设成8000。在网站中添加WCF服务,取名字为:GetAccountService.svc,这时同时生成了一个接口:IGetAccountService.cs和一个实现类:GetAccountService.cs,并且有一个默认方法。我们为了测试对数据库的访问,将方法改为:GetAccount。
完成的代码如下:
1.IGetAccountService.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Runtime.Serialization;usingSystem.ServiceModel;usingSystem.Text;//注意: 如果更改此处的接口名称 "IGetAccountService",也必须更新 Web.config 中对 "IGetAccountService" 的引用。
[ServiceContract]publicinterfaceIGetAccountService
{
[OperationContract]
Account GetAccount(String username);
}
2.GetAccountService.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Runtime.Serialization;usingSystem.ServiceModel;usingSystem.Text;usingSystem.Data;usingSystem.Data.SqlClient;//注意: 如果更改此处的类名 "GetAccountService",也必须更新 Web.config 中对 "GetAccountService" 的引用。publicclassGetAccountService : IGetAccountService
{publicAccount GetAccount(String username)
{
String dbconn =global::System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
String sqlString ="SELECT userId, userName FROM UserAccount where userName='"+username +"'";
Account account =newAccount();using(SqlConnection conn =newSqlConnection(dbconn))
{
conn.Open();
SqlCommand cmd =newSqlCommand();
cmd.Connection =conn;
mandText =sqlString;
SqlDataReader rd =cmd.ExecuteReader();if(rd.Read())
{
account.Userid =Convert.ToInt32(rd["userId"]);
account.Username =rd["userName"].ToString();
}
}returnaccount;
}
}
3.代码涉及到一个Account对象:
usingSystem;usingSystem.Data;usingSystem.Linq;///<summary>///Account 的摘要说明///</summary>publicclassAccount
{privateintm_userid;privateString m_username;publicAccount()
{////TODO: 在此处添加构造函数逻辑//
}publicintUserid
{get{ returnm_userid;}set{ m_userid =value; }
}publicString Username
{get{ returnm_username; }set{ m_username =value; }
}
}
这时,右击GetAccountService.svc选择“在浏览器中查看”,可以看到服务已经运行,并且也打印出了访问服务的URL:“http://localhost:8000/WebWcf/GetAccountService.svc?wsdl”这个时候如果用.net来访问服务是没有问题的,但是如果用Java访问还是不行。程序上并没有错误,只是协议有点小问题。必须将Web.config中的wsHttpBinding改为:basicHttpBinding才行:
<system.serviceModel><behaviors><serviceBehaviors><behavior name="GetAccountServiceBehavior"><serviceMetadata httpGetEnabled="true"/><serviceDebug includeExceptionDetailInFaults="false"/></behavior></serviceBehaviors></behaviors><services><service behaviorConfiguration="GetAccountServiceBehavior"name="GetAccountService"><endpoint address=""binding="basicHttpBinding"contract="IGetAccountService"><identity><dns value="localhost"/></identity></endpoint><endpoint address="mex"binding="mexHttpBinding"contract="IMetadataExchange"/></service></services></system.serviceModel>
好了,现在可以用Java访问了。Java的访问工具比较好用的还是axis,可以到网上下载。有了axis后,可以编写一个脚本,用来生成一些基本代码。例如编写如下一个脚本,并存为wcf.bat文件:
set Axis_Lib=axis-1_4\lib
set Java_Cmd=java -Djava.ext.dirs=%Axis_Lib%
set Output_Path=.
set Package=wcf%Java_Cmd%org.apache.axis.wsdl.WSDL2Java http://localhost:8000/WebWcf/GetAccountService.svc?wsdl -o%Output_Path%-p%Package%
其中的lib为axis工具包中的lib目录,它包含了需要用到的Jar。在Dos下运行wcf.bat,即在当前目录中创建了目录wcf,并生成了五个Java程序,代码分别为:
1. BasicHttpBinding_IGetAccountServiceStub.java
代码 /**
* BasicHttpBinding_IGetAccountServiceStub.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, (06:55:48 PDT) WSDL2Java emitter.*/packagewcf;publicclassBasicHttpBinding_IGetAccountServiceStub extendsorg.apache.axis.client.Stub implementswcf.IGetAccountService {privatejava.util.Vector cachedSerClasses =newjava.util.Vector();privatejava.util.Vector cachedSerQNames =newjava.util.Vector();privatejava.util.Vector cachedSerFactories =newjava.util.Vector();privatejava.util.Vector cachedDeserFactories =newjava.util.Vector();staticorg.apache.axis.description.OperationDesc [] _operations;static{
_operations =neworg.apache.axis.description.OperationDesc[3];
_initOperationDesc1();
}privatestaticvoid_initOperationDesc1(){
org.apache.axis.description.OperationDesc oper;
org.apache.axis.description.ParameterDesc param;
oper =neworg.apache.axis.description.OperationDesc();
oper.setName("GetAccountPass");
param =neworg.apache.axis.description.ParameterDesc(newjavax.xml.namespace.QName("/", "uname"), org.apache.axis.description.ParameterDesc.IN, newjavax.xml.namespace.QName("/2001/XMLSchema", "string"), java.lang.String.class, false, false);
param.setOmittable(true);
param.setNillable(true);
oper.addParameter(param);
oper.setReturnType(newjavax.xml.namespace.QName("/2001/XMLSchema", "string"));
oper.setReturnClass(java.lang.String.class);
oper.setReturnQName(newjavax.xml.namespace.QName("/", "GetAccountPassResult"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
_operations[0] =oper;
oper =neworg.apache.axis.description.OperationDesc();
oper.setName("GetAccountName");
oper.setReturnType(newjavax.xml.namespace.QName("/2001/XMLSchema", "string"));
oper.setReturnClass(java.lang.String.class);
oper.setReturnQName(newjavax.xml.namespace.QName("/", "GetAccountNameResult"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
_operations[1] =oper;
oper =neworg.apache.axis.description.OperationDesc();
oper.setName("GetAccount");
param =neworg.apache.axis.description.ParameterDesc(newjavax.xml.namespace.QName("/", "username"), org.apache.axis.description.ParameterDesc.IN, newjavax.xml.namespace.QName("/2001/XMLSchema", "string"), java.lang.String.class, false, false);
param.setOmittable(true);
param.setNillable(true);
oper.addParameter(param);
oper.setReturnType(newjavax.xml.namespace.QName("//07/", "Account"));
oper.setReturnClass(wcf.Account.class);
oper.setReturnQName(newjavax.xml.namespace.QName("/", "GetAccountResult"));
oper.setStyle(org.apache.axis.constants.Style.WRAPPED);
oper.setUse(org.apache.axis.constants.Use.LITERAL);
_operations[2] =oper;
}publicBasicHttpBinding_IGetAccountServiceStub() throwsorg.apache.axis.AxisFault {this(null);
}publicBasicHttpBinding_IGetAccountServiceStub(.URL endpointURL, javax.xml.rpc.Service service) throwsorg.apache.axis.AxisFault {this(service);super.cachedEndpoint =endpointURL;
}publicBasicHttpBinding_IGetAccountServiceStub(javax.xml.rpc.Service service) throwsorg.apache.axis.AxisFault {if(service ==null) {super.service =neworg.apache.axis.client.Service();
} else{super.service =service;
}
((org.apache.axis.client.Service)super.service).setTypeMappingVersion("1.2");
java.lang.Class cls;
javax.xml.namespace.QName qName;
javax.xml.namespace.QName qName2;
java.lang.Class beansf =org.apache.axis.encoding.ser.BeanSerializerFactory.class;
java.lang.Class beandf =org.apache.axis.encoding.ser.BeanDeserializerFactory.class;
java.lang.Class enumsf =org.apache.axis.encoding.ser.EnumSerializerFactory.class;
java.lang.Class enumdf =org.apache.axis.encoding.ser.EnumDeserializerFactory.class;
java.lang.Class arraysf =org.apache.axis.encoding.ser.ArraySerializerFactory.class;
java.lang.Class arraydf =org.apache.axis.encoding.ser.ArrayDeserializerFactory.class;
java.lang.Class simplesf =org.apache.axis.encoding.ser.SimpleSerializerFactory.class;
java.lang.Class simpledf =org.apache.axis.encoding.ser.SimpleDeserializerFactory.class;
java.lang.Class simplelistsf =org.apache.axis.encoding.ser.SimpleListSerializerFactory.class;
java.lang.Class simplelistdf =org.apache.axis.encoding.ser.SimpleListDeserializerFactory.class;
qName =newjavax.xml.namespace.QName("//07/", "Account");
cachedSerQNames.add(qName);
cls =wcf.Account.class;
cachedSerClasses.add(cls);
cachedSerFactories.add(beansf);
cachedDeserFactories.add(beandf);
}protectedorg.apache.axis.client.Call createCall() throwsjava.rmi.RemoteException {try{
org.apache.axis.client.Call _call =super._createCall();if(super.maintainSessionSet) {
_call.setMaintainSession(super.maintainSession);
}if(super.cachedUsername !=null) {
_call.setUsername(super.cachedUsername);
}if(super.cachedPassword !=null) {
_call.setPassword(super.cachedPassword);
}if(super.cachedEndpoint !=null) {
_call.setTargetEndpointAddress(super.cachedEndpoint);
}if(super.cachedTimeout !=null) {
_call.setTimeout(super.cachedTimeout);
}if(super.cachedPortName !=null) {
_call.setPortName(super.cachedPortName);
}
java.util.Enumeration keys =super.cachedProperties.keys();while(keys.hasMoreElements()) {
java.lang.String key =(java.lang.String) keys.nextElement();
_call.setProperty(key, super.cachedProperties.get(key));
}//All the type mapping information is registered//when the first call is made.//The type mapping information is actually registered in//the TypeMappingRegistry of the service, which//is the reason why registration is only needed for the first call.synchronized(this) {if(firstCall()) {//must set encoding style before registering serializers_call.setEncodingStyle(null);for(inti =0; i <cachedSerFactories.size(); ++i) {
java.lang.Class cls =(java.lang.Class) cachedSerClasses.get(i);
javax.xml.namespace.QName qName =
(javax.xml.namespace.QName) cachedSerQNames.get(i);
java.lang.Object x =cachedSerFactories.get(i);if(x instanceofClass) {
java.lang.Class sf =(java.lang.Class)
cachedSerFactories.get(i);
java.lang.Class df =(java.lang.Class)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}elseif(x instanceofjavax.xml.rpc.encoding.SerializerFactory) {
org.apache.axis.encoding.SerializerFactory sf =(org.apache.axis.encoding.SerializerFactory)
cachedSerFactories.get(i);
org.apache.axis.encoding.DeserializerFactory df =(org.apache.axis.encoding.DeserializerFactory)
cachedDeserFactories.get(i);
_call.registerTypeMapping(cls, qName, sf, df, false);
}
}
}
}return_call;
}catch(java.lang.Throwable _t) {throwneworg.apache.axis.AxisFault("Failure trying to get the Call object", _t);
}
}publicjava.lang.String getAccountPass(java.lang.String uname) throwsjava.rmi.RemoteException {if(super.cachedEndpoint ==null) {throwneworg.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call =createCall();
_call.setOperation(_operations[0]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("/IGetAccountService/GetAccountPass");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(newjavax.xml.namespace.QName("/", "GetAccountPass"));
setRequestHeaders(_call);
setAttachments(_call);try{ java.lang.Object _resp =_call.invoke(newjava.lang.Object[] {uname});if(_resp instanceofjava.rmi.RemoteException) {throw(java.rmi.RemoteException)_resp;
}else{
extractAttachments(_call);try{return(java.lang.String) _resp;
} catch(java.lang.Exception _exception) {return(java.lang.String) org.apache.axis.utils.JavaUtils.convert(_resp, java.lang.String.class);
}
}
} catch(org.apache.axis.AxisFault axisFaultException) {throwaxisFaultException;
}
}publicjava.lang.String getAccountName() throwsjava.rmi.RemoteException {if(super.cachedEndpoint ==null) {throwneworg.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call =createCall();
_call.setOperation(_operations[1]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("/IGetAccountService/GetAccountName");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(newjavax.xml.namespace.QName("/", "GetAccountName"));
setRequestHeaders(_call);
setAttachments(_call);try{ java.lang.Object _resp =_call.invoke(newjava.lang.Object[] {});if(_resp instanceofjava.rmi.RemoteException) {throw(java.rmi.RemoteException)_resp;
}else{
extractAttachments(_call);try{return(java.lang.String) _resp;
} catch(java.lang.Exception _exception) {return(java.lang.String) org.apache.axis.utils.JavaUtils.convert(_resp, java.lang.String.class);
}
}
} catch(org.apache.axis.AxisFault axisFaultException) {throwaxisFaultException;
}
}publicwcf.Account getAccount(java.lang.String username) throwsjava.rmi.RemoteException {if(super.cachedEndpoint ==null) {throwneworg.apache.axis.NoEndPointException();
}
org.apache.axis.client.Call _call =createCall();
_call.setOperation(_operations[2]);
_call.setUseSOAPAction(true);
_call.setSOAPActionURI("/IGetAccountService/GetAccount");
_call.setEncodingStyle(null);
_call.setProperty(org.apache.axis.client.Call.SEND_TYPE_ATTR, Boolean.FALSE);
_call.setProperty(org.apache.axis.AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
_call.setOperationName(newjavax.xml.namespace.QName("/", "GetAccount"));
setRequestHeaders(_call);
setAttachments(_call);try{ java.lang.Object _resp =_call.invoke(newjava.lang.Object[] {username});if(_resp instanceofjava.rmi.RemoteException) {throw(java.rmi.RemoteException)_resp;
}else{
extractAttachments(_call);try{return(wcf.Account) _resp;
} catch(java.lang.Exception _exception) {return(wcf.Account) org.apache.axis.utils.JavaUtils.convert(_resp, wcf.Account.class);
}
}
} catch(org.apache.axis.AxisFault axisFaultException) {throwaxisFaultException;
}
}
}
2. GetAccountService.java
代码 /**
* GetAccountService.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, (06:55:48 PDT) WSDL2Java emitter.*/packagewcf;publicinterfaceGetAccountService extendsjavax.xml.rpc.Service {publicjava.lang.String getBasicHttpBinding_IGetAccountServiceAddress();publicwcf.IGetAccountService getBasicHttpBinding_IGetAccountService() throwsjavax.xml.rpc.ServiceException;publicwcf.IGetAccountService getBasicHttpBinding_IGetAccountService(.URL portAddress) throwsjavax.xml.rpc.ServiceException;
}
3. GetAccountServiceLocator.java
代码 /**
* GetAccountServiceLocator.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, (06:55:48 PDT) WSDL2Java emitter.*/packagewcf;publicclassGetAccountServiceLocator extendsorg.apache.axis.client.Service implementswcf.GetAccountService {publicGetAccountServiceLocator() {
}publicGetAccountServiceLocator(org.apache.axis.EngineConfiguration config) {super(config);
}publicGetAccountServiceLocator(java.lang.String wsdlLoc, javax.xml.namespace.QName sName) throwsjavax.xml.rpc.ServiceException {super(wsdlLoc, sName);
}//Use to get a proxy class for BasicHttpBinding_IGetAccountServiceprivatejava.lang.String BasicHttpBinding_IGetAccountService_address ="http://localhost:8000/WebWcf/GetAccountService.svc";publicjava.lang.String getBasicHttpBinding_IGetAccountServiceAddress() {returnBasicHttpBinding_IGetAccountService_address;
}//The WSDD service name defaults to the port name.privatejava.lang.String BasicHttpBinding_IGetAccountServiceWSDDServiceName ="BasicHttpBinding_IGetAccountService";publicjava.lang.String getBasicHttpBinding_IGetAccountServiceWSDDServiceName() {returnBasicHttpBinding_IGetAccountServiceWSDDServiceName;
}publicvoidsetBasicHttpBinding_IGetAccountServiceWSDDServiceName(java.lang.String name) {
BasicHttpBinding_IGetAccountServiceWSDDServiceName =name;
}publicwcf.IGetAccountService getBasicHttpBinding_IGetAccountService() throwsjavax.xml.rpc.ServiceException {
.URL endpoint;try{
endpoint =.URL(BasicHttpBinding_IGetAccountService_address);
}catch(.MalformedURLException e) {thrownewjavax.xml.rpc.ServiceException(e);
}returngetBasicHttpBinding_IGetAccountService(endpoint);
}publicwcf.IGetAccountService getBasicHttpBinding_IGetAccountService(.URL portAddress) throwsjavax.xml.rpc.ServiceException {try{
wcf.BasicHttpBinding_IGetAccountServiceStub _stub =newwcf.BasicHttpBinding_IGetAccountServiceStub(portAddress, this);
_stub.setPortName(getBasicHttpBinding_IGetAccountServiceWSDDServiceName());return_stub;
}catch(org.apache.axis.AxisFault e) {returnnull;
}
}publicvoidsetBasicHttpBinding_IGetAccountServiceEndpointAddress(java.lang.String address) {
BasicHttpBinding_IGetAccountService_address =address;
}/**
* For the given interface, get the stub implementation.
* If this service has no port for the given interface,
* then ServiceException is thrown.*/publicjava.rmi.Remote getPort(Class serviceEndpointInterface) throwsjavax.xml.rpc.ServiceException {try{if(wcf.IGetAccountService.class.isAssignableFrom(serviceEndpointInterface)) {
wcf.BasicHttpBinding_IGetAccountServiceStub _stub =newwcf.BasicHttpBinding_IGetAccountServiceStub(.URL(BasicHttpBinding_IGetAccountService_address), this);
_stub.setPortName(getBasicHttpBinding_IGetAccountServiceWSDDServiceName());return_stub;
}
}catch(java.lang.Throwable t) {thrownewjavax.xml.rpc.ServiceException(t);
}thrownewjavax.xml.rpc.ServiceException("There is no stub implementation for the interface: "+(serviceEndpointInterface ==null?"null": serviceEndpointInterface.getName()));
}/**
* For the given interface, get the stub implementation.
* If this service has no port for the given interface,
* then ServiceException is thrown.*/publicjava.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throwsjavax.xml.rpc.ServiceException {if(portName ==null) {returngetPort(serviceEndpointInterface);
}
java.lang.String inputPortName =portName.getLocalPart();if("BasicHttpBinding_IGetAccountService".equals(inputPortName)) {returngetBasicHttpBinding_IGetAccountService();
}else{
java.rmi.Remote _stub =getPort(serviceEndpointInterface);
((org.apache.axis.client.Stub) _stub).setPortName(portName);return_stub;
}
}publicjavax.xml.namespace.QName getServiceName() {returnnewjavax.xml.namespace.QName("/", "GetAccountService");
}privatejava.util.HashSet ports =null;publicjava.util.Iterator getPorts() {if(ports ==null) {
ports =newjava.util.HashSet();
ports.add(newjavax.xml.namespace.QName("/", "BasicHttpBinding_IGetAccountService"));
}returnports.iterator();
}/**
* Set the endpoint address for the specified port name.*/publicvoidsetEndpointAddress(java.lang.String portName, java.lang.String address) throwsjavax.xml.rpc.ServiceException {if("BasicHttpBinding_IGetAccountService".equals(portName)) {
setBasicHttpBinding_IGetAccountServiceEndpointAddress(address);
}else
{ //Unknown Port Namethrownewjavax.xml.rpc.ServiceException("Cannot set Endpoint Address for Unknown Port"+portName);
}
}/**
* Set the endpoint address for the specified port name.*/publicvoidsetEndpointAddress(javax.xml.namespace.QName portName, java.lang.String address) throwsjavax.xml.rpc.ServiceException {
setEndpointAddress(portName.getLocalPart(), address);
}
}
4. IGetAccountService.java
代码 /**
* IGetAccountService.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, (06:55:48 PDT) WSDL2Java emitter.*/packagewcf;publicinterfaceIGetAccountService extendsjava.rmi.Remote {publicjava.lang.String getAccountPass(java.lang.String uname) throwsjava.rmi.RemoteException;publicjava.lang.String getAccountName() throwsjava.rmi.RemoteException;publicwcf.Account getAccount(java.lang.String username) throwsjava.rmi.RemoteException;
}
5. Account.java
代码 /**
* Account.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, (06:55:48 PDT) WSDL2Java emitter.*/packagewcf;publicclassAccount implementsjava.io.Serializable {privatejava.lang.Integer userid;privatejava.lang.String username;publicAccount() {
}publicAccount(
java.lang.Integer userid,
java.lang.String username) {this.userid =userid;this.username =username;
}/**
* Gets the userid value for this Account.
*
* @returnuserid*/publicjava.lang.Integer getUserid() {returnuserid;
}/**
* Sets the userid value for this Account.
*
* @paramuserid*/publicvoidsetUserid(java.lang.Integer userid) {this.userid =userid;
}/**
* Gets the username value for this Account.
*
* @returnusername*/publicjava.lang.String getUsername() {returnusername;
}/**
* Sets the username value for this Account.
*
* @paramusername*/publicvoidsetUsername(java.lang.String username) {this.username =username;
}privatejava.lang.Object __equalsCalc =null;publicsynchronizedbooleanequals(java.lang.Object obj) {if(!(obj instanceofAccount)) returnfalse;
Account other =(Account) obj;if(obj ==null) returnfalse;if(this==obj) returntrue;if(__equalsCalc !=null) {return(__equalsCalc ==obj);
}
__equalsCalc =obj;boolean_equals;
_equals =true&&
((this.userid==null&&other.getUserid()==null) ||
(this.userid!=null&&this.userid.equals(other.getUserid()))) &&
((this.username==null&&other.getUsername()==null) ||
(this.username!=null&&this.username.equals(other.getUsername())));
__equalsCalc =null;return_equals;
}privateboolean__hashCodeCalc =false;publicsynchronizedinthashCode() {if(__hashCodeCalc) {return0;
}
__hashCodeCalc =true;int_hashCode =1;if(getUserid() !=null) {
_hashCode +=getUserid().hashCode();
}if(getUsername() !=null) {
_hashCode +=getUsername().hashCode();
}
__hashCodeCalc =false;return_hashCode;
}//Type metadataprivatestaticorg.apache.axis.description.TypeDesc typeDesc =neworg.apache.axis.description.TypeDesc(Account.class, true);static{
typeDesc.setXmlType(newjavax.xml.namespace.QName("//07/", "Account"));
org.apache.axis.description.ElementDesc elemField =neworg.apache.axis.description.ElementDesc();
elemField.setFieldName("userid");
elemField.setXmlName(newjavax.xml.namespace.QName("//07/", "Userid"));
elemField.setXmlType(newjavax.xml.namespace.QName("/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField =neworg.apache.axis.description.ElementDesc();
elemField.setFieldName("username");
elemField.setXmlName(newjavax.xml.namespace.QName("//07/", "Username"));
elemField.setXmlType(newjavax.xml.namespace.QName("/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(true);
typeDesc.addFieldDesc(elemField);
}/**
* Return type metadata object*/publicstaticorg.apache.axis.description.TypeDesc getTypeDesc() {returntypeDesc;
}/**
* Get Custom Serializer*/publicstaticorg.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {returnneworg.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}/**
* Get Custom Deserializer*/publicstaticorg.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {returnneworg.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
用上面代码可以用Eclipse创建一个Java测试工程,并将axis工具包Lib的Jar也导入工程中,再创建一个测试程序:ClientTest.java
packagewcf;publicclassClientTest {/**
* @paramargs*/publicstaticvoidmain(String[] args) {try{
GetAccountService client =newGetAccountServiceLocator();
Account account =newAccount();
account =client.getBasicHttpBinding_IGetAccountService().getAccount("abc");
System.out.println("account="+account.getUserid()+";"+account.getUsername());
System.in.read();
} catch(Exception e) {
System.out.println("Exception : "+e.getMessage());
}
}
}
确认WCF服务正在运行中,在Eclipse中打开上面程序,点击Run菜单,选择”Run as Java Application”,即可打印出运行结果:
account=1;abc
转:/chrischen662/archive//08/15/1800130.html
如果觉得《Java调用wcf》对你有帮助,请点赞、收藏,并留下你的观点哦!