• Java调用wcf


    使用分布式编程,很方便不同编程语言之间互相访问,但也必须注意一些技术细节,实现起来才能畅通无阻,取得事半功倍的效果。

    首先,创建一个WCF。使用原有网站或新建一个网站,并将端口动态改为固定,如设成8000。在网站中添加WCF服务,取名字为:GetAccountService.svc,这时同时生成了一个接口:IGetAccountService.cs和一个实现类:GetAccountService.cs,并且有一个默认方法。我们为了测试对数据库的访问,将方法改为:GetAccount。

    完成的代码如下:

    1.IGetAccountService.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
     
    // 注意: 如果更改此处的接口名称 "IGetAccountService",也必须更新 Web.config 中对 "IGetAccountService" 的引用。
    [ServiceContract]
    public interface IGetAccountService
    {
        [OperationContract]
        Account GetAccount(String username);
    }

    2.GetAccountService.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    using System.Data;
    using System.Data.SqlClient;
    // 注意: 如果更改此处的类名 "GetAccountService",也必须更新 Web.config 中对 "GetAccountService" 的引用。
    public class GetAccountService : IGetAccountService
    {
        public Account GetAccount(String username)
        {
          String dbconn = global::System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            String sqlString = "SELECT userId, userName FROM UserAccount where userName='" + username + "'";
            Account account = new Account();
            using (SqlConnection conn = new SqlConnection(dbconn))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = sqlString;
                SqlDataReader rd = cmd.ExecuteReader();
                if (rd.Read())
                {
                    account.Userid = Convert.ToInt32(rd["userId"]);
                    account.Username = rd["userName"].ToString();
                }
            }
            return account;
        }
    }

    3.代码涉及到一个Account对象:

    using System;
    
    using System.Data;
    
    using System.Linq;
    
    /// <summary>
    
    ///Account 的摘要说明
    
    /// </summary>
    
    public class Account
    
    {
    
        private int m_userid;
    
        private String m_username;
    
     
    
        public Account()
    
        {
    
            //
    
            //TODO: 在此处添加构造函数逻辑
    
            //
    
        }
    
     
    
        public int Userid
    
        {
    
            get{ return m_userid;}
    
            set { m_userid = value; }
    
        }
    
     
    
        public String Username
    
        {
    
            get { return m_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>
    View Code

    好了,现在可以用Java访问了。Java的访问工具比较好用的还是axis,可以到网上下载。有了axis后,可以编写一个脚本,用来生成一些基本代码。例如编写如下一个脚本,并存为wcf.bat文件:

    复制代码
    set Axis_Lib=axis-1_4lib 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, 2006 (06:55:48 PDT) WSDL2Java emitter.
     */
    
    package wcf;
    
    public class BasicHttpBinding_IGetAccountServiceStub extends org.apache.axis.client.Stub implements wcf.IGetAccountService {
        private java.util.Vector cachedSerClasses = new java.util.Vector();
        private java.util.Vector cachedSerQNames = new java.util.Vector();
        private java.util.Vector cachedSerFactories = new java.util.Vector();
        private java.util.Vector cachedDeserFactories = new java.util.Vector();
    
        static org.apache.axis.description.OperationDesc [] _operations;
    
        static {
            _operations = new org.apache.axis.description.OperationDesc[3];
            _initOperationDesc1();
        }
    
        private static void _initOperationDesc1(){
            org.apache.axis.description.OperationDesc oper;
            org.apache.axis.description.ParameterDesc param;
            oper = new org.apache.axis.description.OperationDesc();
            oper.setName("GetAccountPass");
            param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("http://tempuri.org/", "uname"), org.apache.axis.description.ParameterDesc.IN, new javax.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(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
            oper.setReturnClass(java.lang.String.class);
            oper.setReturnQName(new javax.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 = new org.apache.axis.description.OperationDesc();
            oper.setName("GetAccountName");
            oper.setReturnType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
            oper.setReturnClass(java.lang.String.class);
            oper.setReturnQName(new javax.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 = new org.apache.axis.description.OperationDesc();
            oper.setName("GetAccount");
            param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("http://tempuri.org/", "username"), org.apache.axis.description.ParameterDesc.IN, new javax.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(new javax.xml.namespace.QName("http://schemas.datacontract.org/2004/07/", "Account"));
            oper.setReturnClass(wcf.Account.class);
            oper.setReturnQName(new javax.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;
    
        }
    
        public BasicHttpBinding_IGetAccountServiceStub() throws org.apache.axis.AxisFault {
             this(null);
        }
    
        public BasicHttpBinding_IGetAccountServiceStub(java.net.URL endpointURL, javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
             this(service);
             super.cachedEndpoint = endpointURL;
        }
    
        public BasicHttpBinding_IGetAccountServiceStub(javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
            if (service == null) {
                super.service = new org.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 = new javax.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);
    
        }
    
        protected org.apache.axis.client.Call createCall() throws java.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 (int i = 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 instanceof Class) {
                                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);
                            }
                            else if (x instanceof javax.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) {
                throw new org.apache.axis.AxisFault("Failure trying to get the Call object", _t);
            }
        }
    
        public java.lang.String getAccountPass(java.lang.String uname) throws java.rmi.RemoteException {
            if (super.cachedEndpoint == null) {
                throw new org.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(new javax.xml.namespace.QName("http://tempuri.org/", "GetAccountPass"));
    
            setRequestHeaders(_call);
            setAttachments(_call);
     try {        java.lang.Object _resp = _call.invoke(new java.lang.Object[] {uname});
    
            if (_resp instanceof java.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) {
      throw axisFaultException;
    }
        }
    
        public java.lang.String getAccountName() throws java.rmi.RemoteException {
            if (super.cachedEndpoint == null) {
                throw new org.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(new javax.xml.namespace.QName("http://tempuri.org/", "GetAccountName"));
    
            setRequestHeaders(_call);
            setAttachments(_call);
     try {        java.lang.Object _resp = _call.invoke(new java.lang.Object[] {});
    
            if (_resp instanceof java.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) {
      throw axisFaultException;
    }
        }
    
        public wcf.Account getAccount(java.lang.String username) throws java.rmi.RemoteException {
            if (super.cachedEndpoint == null) {
                throw new org.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(new javax.xml.namespace.QName("http://tempuri.org/", "GetAccount"));
    
            setRequestHeaders(_call);
            setAttachments(_call);
     try {        java.lang.Object _resp = _call.invoke(new java.lang.Object[] {username});
    
            if (_resp instanceof java.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) {
      throw axisFaultException;
    }
        }
    
    }
    View Code

    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.
     */
    
    package wcf;
    
    public interface GetAccountService extends javax.xml.rpc.Service {
        public java.lang.String getBasicHttpBinding_IGetAccountServiceAddress();
    
        public wcf.IGetAccountService getBasicHttpBinding_IGetAccountService() throws javax.xml.rpc.ServiceException;
    
        public wcf.IGetAccountService getBasicHttpBinding_IGetAccountService(java.net.URL portAddress) throws javax.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.
     */
    
    package wcf;
    
    public class GetAccountServiceLocator extends org.apache.axis.client.Service implements wcf.GetAccountService {
    
        public GetAccountServiceLocator() {
        }
    
    
        public GetAccountServiceLocator(org.apache.axis.EngineConfiguration config) {
            super(config);
        }
    
        public GetAccountServiceLocator(java.lang.String wsdlLoc, javax.xml.namespace.QName sName) throws javax.xml.rpc.ServiceException {
            super(wsdlLoc, sName);
        }
    
        // Use to get a proxy class for BasicHttpBinding_IGetAccountService
        private java.lang.String BasicHttpBinding_IGetAccountService_address = "http://localhost:8000/WebWcf/GetAccountService.svc";
    
        public java.lang.String getBasicHttpBinding_IGetAccountServiceAddress() {
            return BasicHttpBinding_IGetAccountService_address;
        }
    
        // The WSDD service name defaults to the port name.
        private java.lang.String BasicHttpBinding_IGetAccountServiceWSDDServiceName = "BasicHttpBinding_IGetAccountService";
    
        public java.lang.String getBasicHttpBinding_IGetAccountServiceWSDDServiceName() {
            return BasicHttpBinding_IGetAccountServiceWSDDServiceName;
        }
    
        public void setBasicHttpBinding_IGetAccountServiceWSDDServiceName(java.lang.String name) {
            BasicHttpBinding_IGetAccountServiceWSDDServiceName = name;
        }
    
        public wcf.IGetAccountService getBasicHttpBinding_IGetAccountService() throws javax.xml.rpc.ServiceException {
           java.net.URL endpoint;
            try {
                endpoint = new java.net.URL(BasicHttpBinding_IGetAccountService_address);
            }
            catch (java.net.MalformedURLException e) {
                throw new javax.xml.rpc.ServiceException(e);
            }
            return getBasicHttpBinding_IGetAccountService(endpoint);
        }
    
        public wcf.IGetAccountService getBasicHttpBinding_IGetAccountService(java.net.URL portAddress) throws javax.xml.rpc.ServiceException {
            try {
                wcf.BasicHttpBinding_IGetAccountServiceStub _stub = new wcf.BasicHttpBinding_IGetAccountServiceStub(portAddress, this);
                _stub.setPortName(getBasicHttpBinding_IGetAccountServiceWSDDServiceName());
                return _stub;
            }
            catch (org.apache.axis.AxisFault e) {
                return null;
            }
        }
    
        public void setBasicHttpBinding_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.
         */
        public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
            try {
                if (wcf.IGetAccountService.class.isAssignableFrom(serviceEndpointInterface)) {
                    wcf.BasicHttpBinding_IGetAccountServiceStub _stub = new wcf.BasicHttpBinding_IGetAccountServiceStub(new java.net.URL(BasicHttpBinding_IGetAccountService_address), this);
                    _stub.setPortName(getBasicHttpBinding_IGetAccountServiceWSDDServiceName());
                    return _stub;
                }
            }
            catch (java.lang.Throwable t) {
                throw new javax.xml.rpc.ServiceException(t);
            }
            throw new javax.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.
         */
        public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
            if (portName == null) {
                return getPort(serviceEndpointInterface);
            }
            java.lang.String inputPortName = portName.getLocalPart();
            if ("BasicHttpBinding_IGetAccountService".equals(inputPortName)) {
                return getBasicHttpBinding_IGetAccountService();
            }
            else  {
                java.rmi.Remote _stub = getPort(serviceEndpointInterface);
                ((org.apache.axis.client.Stub) _stub).setPortName(portName);
                return _stub;
            }
        }
    
        public javax.xml.namespace.QName getServiceName() {
            return new javax.xml.namespace.QName("http://tempuri.org/", "GetAccountService");
        }
    
        private java.util.HashSet ports = null;
    
        public java.util.Iterator getPorts() {
            if (ports == null) {
                ports = new java.util.HashSet();
                ports.add(new javax.xml.namespace.QName("http://tempuri.org/", "BasicHttpBinding_IGetAccountService"));
            }
            return ports.iterator();
        }
    
        /**
        * Set the endpoint address for the specified port name.
        */
        public void setEndpointAddress(java.lang.String portName, java.lang.String address) throws javax.xml.rpc.ServiceException {
            
    if ("BasicHttpBinding_IGetAccountService".equals(portName)) {
                setBasicHttpBinding_IGetAccountServiceEndpointAddress(address);
            }
            else 
    { // Unknown Port Name
                throw new javax.xml.rpc.ServiceException(" Cannot set Endpoint Address for Unknown Port" + portName);
            }
        }
    
        /**
        * Set the endpoint address for the specified port name.
        */
        public void setEndpointAddress(javax.xml.namespace.QName portName, java.lang.String address) throws javax.xml.rpc.ServiceException {
            setEndpointAddress(portName.getLocalPart(), address);
        }
    
    }
    View Code

    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.
     */
    
    package wcf;
    
    public interface IGetAccountService extends java.rmi.Remote {
        public java.lang.String getAccountPass(java.lang.String uname) throws java.rmi.RemoteException;
        public java.lang.String getAccountName() throws java.rmi.RemoteException;
        public wcf.Account getAccount(java.lang.String username) throws java.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.
     */
    
    package wcf;
    
    public class Account  implements java.io.Serializable {
        private java.lang.Integer userid;
    
        private java.lang.String username;
    
        public Account() {
        }
    
        public Account(
               java.lang.Integer userid,
               java.lang.String username) {
               this.userid = userid;
               this.username = username;
        }
    
    
        /**
         * Gets the userid value for this Account.
         * 
         * @return userid
         */
        public java.lang.Integer getUserid() {
            return userid;
        }
    
    
        /**
         * Sets the userid value for this Account.
         * 
         * @param userid
         */
        public void setUserid(java.lang.Integer userid) {
            this.userid = userid;
        }
    
    
        /**
         * Gets the username value for this Account.
         * 
         * @return username
         */
        public java.lang.String getUsername() {
            return username;
        }
    
    
        /**
         * Sets the username value for this Account.
         * 
         * @param username
         */
        public void setUsername(java.lang.String username) {
            this.username = username;
        }
    
        private java.lang.Object __equalsCalc = null;
        public synchronized boolean equals(java.lang.Object obj) {
            if (!(obj instanceof Account)) return false;
            Account other = (Account) obj;
            if (obj == null) return false;
            if (this == obj) return true;
            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;
        }
    
        private boolean __hashCodeCalc = false;
        public synchronized int hashCode() {
            if (__hashCodeCalc) {
                return 0;
            }
            __hashCodeCalc = true;
            int _hashCode = 1;
            if (getUserid() != null) {
                _hashCode += getUserid().hashCode();
            }
            if (getUsername() != null) {
                _hashCode += getUsername().hashCode();
            }
            __hashCodeCalc = false;
            return _hashCode;
        }
    
        // Type metadata
        private static org.apache.axis.description.TypeDesc typeDesc =
            new org.apache.axis.description.TypeDesc(Account.class, true);
    
        static {
            typeDesc.setXmlType(new javax.xml.namespace.QName("http://schemas.datacontract.org/2004/07/", "Account"));
            org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
            elemField.setFieldName("userid");
            elemField.setXmlName(new javax.xml.namespace.QName("http://schemas.datacontract.org/2004/07/", "Userid"));
            elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
            elemField.setMinOccurs(0);
            elemField.setNillable(false);
            typeDesc.addFieldDesc(elemField);
            elemField = new org.apache.axis.description.ElementDesc();
            elemField.setFieldName("username");
            elemField.setXmlName(new javax.xml.namespace.QName("http://schemas.datacontract.org/2004/07/", "Username"));
            elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
            elemField.setMinOccurs(0);
            elemField.setNillable(true);
            typeDesc.addFieldDesc(elemField);
        }
    
        /**
         * Return type metadata object
         */
        public static org.apache.axis.description.TypeDesc getTypeDesc() {
            return typeDesc;
        }
    
        /**
         * Get Custom Serializer
         */
        public static org.apache.axis.encoding.Serializer getSerializer(
               java.lang.String mechType, 
               java.lang.Class _javaType,  
               javax.xml.namespace.QName _xmlType) {
            return 
              new  org.apache.axis.encoding.ser.BeanSerializer(
                _javaType, _xmlType, typeDesc);
        }
    
        /**
         * Get Custom Deserializer
         */
        public static org.apache.axis.encoding.Deserializer getDeserializer(
               java.lang.String mechType, 
               java.lang.Class _javaType,  
               javax.xml.namespace.QName _xmlType) {
            return 
              new  org.apache.axis.encoding.ser.BeanDeserializer(
                _javaType, _xmlType, typeDesc);
        }
    
    }
    View Code

    用上面代码可以用Eclipse创建一个Java测试工程,并将axis工具包Lib的Jar也导入工程中,再创建一个测试程序:ClientTest.java

    package wcf;
    
    public class ClientTest {
       /**
        * @param args
        */
       public static void main(String[] args) {
    
        try {
         GetAccountService client = new GetAccountServiceLocator();
         Account account = new Account();
         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
  • 相关阅读:
    将图片部署在tomcat/iportWork/uploadFiles中
    idea中的svn配置
    mavan和idea的搭建,很好的一篇文章
    C#如何遍历数组?
    java 泛型小小的测试题
    js关于变量作为if条件的真假问题
    HTML5实现两个视频循环播放!
    JQuery利用选择器定位动态id?
    hibernate QBC查询
    mybatis前台传来一个String,后后台执行sql变成了true
  • 原文地址:https://www.cnblogs.com/jameslif/p/3414442.html
Copyright © 2020-2023  润新知