Java调用wcf
使用分布式編程,很方便不同編程語(yǔ)言之間互相訪問(wèn),但也必須注意一些技術(shù)細(xì)節(jié),實(shí)現(xiàn)起來(lái)才能暢通無(wú)阻,取得事半功倍的效果。
首先,創(chuàng)建一個(gè)WCF。使用原有網(wǎng)站或新建一個(gè)網(wǎng)站,并將端口動(dòng)態(tài)改為固定,如設(shè)成8000。在網(wǎng)站中添加WCF服務(wù),取名字為:GetAccountService.svc,這時(shí)同時(shí)生成了一個(gè)接口:IGetAccountService.cs和一個(gè)實(shí)現(xiàn)類:GetAccountService.cs,并且有一個(gè)默認(rèn)方法。我們?yōu)榱藴y(cè)試對(duì)數(shù)據(jù)庫(kù)的訪問(wèn),將方法改為:GetAccount。
完成的代碼如下:
1.IGetAccountService.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Runtime.Serialization;usingSystem.ServiceModel;usingSystem.Text;//注意: 如果更改此處的接口名稱 "IGetAccountService",也必須更新 Web.config 中對(duì) "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 中對(duì) "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;
cmd.CommandText =sqlString;
SqlDataReader rd =cmd.ExecuteReader();if(rd.Read())
{
account.Userid =Convert.ToInt32(rd["userId"]);
account.Username =rd["userName"].ToString();
}
}returnaccount;
}
}
3.代碼涉及到一個(gè)Account對(duì)象:
usingSystem;usingSystem.Data;usingSystem.Linq;///<summary>///Account 的摘要說(shuō)明///</summary>publicclassAccount{privateintm_userid;privateString m_username;publicAccount()
{////TODO: 在此處添加構(gòu)造函數(shù)邏輯//
}publicintUserid
{get{ returnm_userid;}set{ m_userid =value; }
}publicString Username
{get{ returnm_username; }set{ m_username =value; }
}
}
這時(shí),右擊GetAccountService.svc選擇“在瀏覽器中查看”,可以看到服務(wù)已經(jīng)運(yùn)行,并且也打印出了訪問(wèn)服務(wù)的URL:“http://localhost:8000/WebWcf/GetAccountService.svc?wsdl”這個(gè)時(shí)候如果用.net來(lái)訪問(wèn)服務(wù)是沒(méi)有問(wèn)題的,但是如果用Java訪問(wèn)還是不行。程序上并沒(méi)有錯(cuò)誤,只是協(xié)議有點(diǎn)小問(wèn)題。必須將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>好了,現(xiàn)在可以用Java訪問(wèn)了。Java的訪問(wèn)工具比較好用的還是axis,可以到網(wǎng)上下載。有了axis后,可以編寫一個(gè)腳本,用來(lái)生成一些基本代碼。例如編寫如下一個(gè)腳本,并存為wcf.bat文件:
set Axis_Lib=axis-1_4\libset 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下運(yùn)行wcf.bat,即在當(dāng)前目錄中創(chuàng)建了目錄wcf,并生成了五個(gè)Java程序,代碼分別為:
1.? BasicHttpBinding_IGetAccountServiceStub.java
代碼 /*** BasicHttpBinding_IGetAccountServiceStub.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (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("http://tempuri.org/", "uname"), org.apache.axis.description.ParameterDesc.IN, newjavax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"), java.lang.String.class, false, false);
param.setOmittable(true);
param.setNillable(true);
oper.addParameter(param);
oper.setReturnType(newjavax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
oper.setReturnClass(java.lang.String.class);
oper.setReturnQName(newjavax.xml.namespace.QName("http://tempuri.org/", "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("http://www.w3.org/2001/XMLSchema", "string"));
oper.setReturnClass(java.lang.String.class);
oper.setReturnQName(newjavax.xml.namespace.QName("http://tempuri.org/", "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("http://tempuri.org/", "username"), org.apache.axis.description.ParameterDesc.IN, newjavax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"), java.lang.String.class, false, false);
param.setOmittable(true);
param.setNillable(true);
oper.addParameter(param);
oper.setReturnType(newjavax.xml.namespace.QName("http://schemas.datacontract.org/2004/07/", "Account"));
oper.setReturnClass(wcf.Account.class);
oper.setReturnQName(newjavax.xml.namespace.QName("http://tempuri.org/", "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(java.net.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("http://schemas.datacontract.org/2004/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("http://tempuri.org/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("http://tempuri.org/", "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("http://tempuri.org/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("http://tempuri.org/", "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("http://tempuri.org/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("http://tempuri.org/", "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, 2006 (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(java.net.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, 2006 (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 {
java.net.URL endpoint;try{
endpoint =newjava.net.URL(BasicHttpBinding_IGetAccountService_address);
}catch(java.net.MalformedURLException e) {thrownewjavax.xml.rpc.ServiceException(e);
}returngetBasicHttpBinding_IGetAccountService(endpoint);
}publicwcf.IGetAccountService getBasicHttpBinding_IGetAccountService(java.net.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(newjava.net.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("http://tempuri.org/", "GetAccountService");
}privatejava.util.HashSet ports =null;publicjava.util.Iterator getPorts() {if(ports ==null) {
ports =newjava.util.HashSet();
ports.add(newjavax.xml.namespace.QName("http://tempuri.org/", "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, 2006 (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, 2006 (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("http://schemas.datacontract.org/2004/07/", "Account"));
org.apache.axis.description.ElementDesc elemField =neworg.apache.axis.description.ElementDesc();
elemField.setFieldName("userid");
elemField.setXmlName(newjavax.xml.namespace.QName("http://schemas.datacontract.org/2004/07/", "Userid"));
elemField.setXmlType(newjavax.xml.namespace.QName("http://www.w3.org/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("http://schemas.datacontract.org/2004/07/", "Username"));
elemField.setXmlType(newjavax.xml.namespace.QName("http://www.w3.org/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創(chuàng)建一個(gè)Java測(cè)試工程,并將axis工具包Lib的Jar也導(dǎo)入工程中,再創(chuàng)建一個(gè)測(cè)試程序: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());
}
}
}
確認(rèn)WCF服務(wù)正在運(yùn)行中,在Eclipse中打開上面程序,點(diǎn)擊Run菜單,選擇”Run as Java Application”,即可打印出運(yùn)行結(jié)果:
account=1;abc轉(zhuǎn):http://www.cnblogs.com/chrischen662/archive/2010/08/15/1800130.html
總結(jié)
- 上一篇: 分享WCF聊天程序--WCFChat
- 下一篇: 柯南贴吧米(柯南贴吧)