一个简单的模拟用户名是否存在的基于契约优先WSDL的webservice开发实例

本文提供了一个简单的示例,演示如何基于契约优先的WSDL开发一个检查用户名是否存在的Webservice服务。从创建WSDL文件开始,通过wsimport生成服务端和客户端代码,然后实现服务端接口并发布服务,最后编写客户端测试类进行调用验证。
摘要由CSDN通过智能技术生成
服务端

新建java工程MyWebservice,在类路径下新建META-INF/wsdl目录,新建check.wsdl文件
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
                  xmlns:tns="http://www.example.org/check/" 
                  xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" 
                  xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
                  name="CheckUserService" 
                  targetNamespace="http://www.example.org/check/">
  <!-- 定义类型 -->
  <wsdl:types>
    <xsd:schema targetNamespace="http://www.example.org/check/">
      <xsd:element name="checkUser" type="tns:checkUserType" />
      <xsd:element name="checkUserResponse" type="tns:checkUserResponseType" />
      
      <xsd:complexType name="checkUserType">
         <xsd:sequence>
           <xsd:element name="userName" type="xsd:string"></xsd:element>
         </xsd:sequence>
      </xsd:complexType>
      
      <xsd:complexType name="checkUserResponseType">
         <xsd:sequence>
           <xsd:element name="checkUserResult" type="xsd:boolean"></xsd:element>
         </xsd:sequence>
      </xsd:complexType>
      
    </xsd:schema>
  </wsdl:types>
  
  <!-- 定义消息 -->
  <wsdl:message name="checkUserRequest">
    <wsdl:part element="tns:checkUser" name="parameters"/>
  </wsdl:message>
  <wsdl:message name="checkUserResponse">
    <wsdl:part element="tns:checkUserResponse" name="parameters"/>
  </wsdl:message>
  
  <wsdl:portType name="ICheckUserService">
    <wsdl:operation name="checkUser">
      <wsdl:input message="tns:checkUserRequest"/>
      <wsdl:output message="tns:checkUserResponse"/>
    </wsdl:operation>
  </wsdl:portType>
  
  <wsdl:binding name="checkUserSOAP" type="tns:ICheckUserService">
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <wsdl:operation name="checkUser">
      <wsdl:input>
        <soap:body use="literal"/>
      </wsdl:input>
      <wsdl:output>
        <soap:body use="literal"/>
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  
  <wsdl:service name="CheckUserService">
    <wsdl:port binding="tns:checkUserSOAP" name="CheckUserPort">
      <soap:address location="http://127.0.0.1:9090/cu/"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

使用wsimport命令生成服务端代码, 在cmd下进到wsdl文件目录下
wsimport -d G:\workspace\EclipseWorkspaceNew\MyWebservice\src -keep -verbose check.wsdl

-d 表示生成的文件保存路径,这里我直接保存在工程的src目录下,完成之后刷新工程即可看到生成的java代码
生成的接口如下
package org.example.check;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.6 in JDK 6
 * Generated source version: 2.1
 * 
 */
@WebService(name = "ICheckUserService", targetNamespace = "http://www.example.org/check/")
@XmlSeeAlso({
    ObjectFactory.class
})
public interface ICheckUserService {


    /**
     * 
     * @param userName
     * @return
     *     returns boolean
     */
    @WebMethod
    @WebResult(name = "checkUserResult", targetNamespace = "")
    @RequestWrapper(localName = "checkUser", targetNamespace = "http://www.example.org/check/", className = "org.example.check.CheckUserType")
    @ResponseWrapper(localName = "checkUserResponse", targetNamespace = "http://www.example.org/check/", className = "org.example.check.CheckUserResponseType")
    public boolean checkUser(
        @WebParam(name = "userName", targetNamespace = "")
        String userName);

}

编写这个接口的实现类,并指定wsdl文件,如下
package qlj.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.jws.WebService;

import org.example.check.ICheckUserService;


@WebService(endpointInterface="org.example.check.ICheckUserService",
            targetNamespace="http://www.example.org/check/",
            wsdlLocation="META-INF/wsdl/check.wsdl")
public class CheckUser implements ICheckUserService {
	private static List<String> users = new ArrayList<String>();

	{
		users.add("aa");
		users.add("bb");
		users.add("cc");
		users.add("dd");
		System.out.println("add complete");
	}
	
	@Override
	public boolean checkUser(String userName) {
		System.out.println(userName);
		return users.contains(userName);//模拟用户是否存在
	}

	
}
这个实现类的类名必须是CheckUser(wsdl文件定义的服务name属性为CheckUserService,把后缀Service去掉 ),否则发布服务时会报错
编写测试类手动发布服务
package qlj.service.main;

import javax.xml.ws.Endpoint;

import qlj.service.impl.CheckUser;


public class ServicePublish {

	public static void main(String[] args) {
		Endpoint.publish("http://127.0.0.1:9090/cu/", new CheckUser());
	}
}
这里的发布地址就是wsdl文件里soap:address中定义的location的属性值

用浏览器访问http://127.0.0.1:9090/cu/?wsdl结果如下
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.example.org/check/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="CheckUserService" targetNamespace="http://www.example.org/check/">
<!--  定义类型  -->
<wsdl:types>
<xsd:schema targetNamespace="http://www.example.org/check/">
<xsd:element name="checkUser" type="tns:checkUserType"/>
<xsd:element name="checkUserResponse" type="tns:checkUserResponseType"/>
<xsd:complexType name="checkUserType">
<xsd:sequence>
<xsd:element name="userName" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="checkUserResponseType">
<xsd:sequence>
<xsd:element name="checkUserResult" type="xsd:boolean"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
</wsdl:types>
<!--  定义消息  -->
<wsdl:message name="checkUserRequest">
<wsdl:part element="tns:checkUser" name="parameters"/>
</wsdl:message>
<wsdl:message name="checkUserResponse">
<wsdl:part element="tns:checkUserResponse" name="parameters"/>
</wsdl:message>
<wsdl:portType name="ICheckUserService">
<wsdl:operation name="checkUser">
<wsdl:input message="tns:checkUserRequest"/>
<wsdl:output message="tns:checkUserResponse"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="checkUserSOAP" type="tns:ICheckUserService">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="checkUser">
<wsdl:input>
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="CheckUserService">
<wsdl:port binding="tns:checkUserSOAP" name="CheckUserPort">
<soap:address location="http://127.0.0.1:9090/cu/"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

服务发布成功!

客户端

新建java工程MyWebservice_client,在cmd下使用wsimport命令,如下
wsimport -d G:\workspace\EclipseWorkspaceNew\MyWebservice_client\src -keep -verbose http://127.0.0.1:9090/cu/?wsdl

把生成的文件保存到工程的src目录下,刷新工程即可看到这些java源码
生成的接口跟上面说的接口ICheckUserService一样
另外有一个CheckUserService类继承了javax.xml.ws.Service,这个类提供了获取ICheckUserService的方法,如下
package org.example.check;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.6 in JDK 6
 * Generated source version: 2.1
 * 
 */
@WebServiceClient(name = "CheckUserService", targetNamespace = "http://www.example.org/check/", wsdlLocation = "http://127.0.0.1:9090/cu/?wsdl")
public class CheckUserService
    extends Service
{

    private final static URL CHECKUSERSERVICE_WSDL_LOCATION;
    private final static Logger logger = Logger.getLogger(org.example.check.CheckUserService.class.getName());

    static {
        URL url = null;
        try {
            URL baseUrl;
            baseUrl = org.example.check.CheckUserService.class.getResource(".");
            url = new URL(baseUrl, "http://127.0.0.1:9090/cu/?wsdl");
        } catch (MalformedURLException e) {
            logger.warning("Failed to create URL for the wsdl Location: 'http://127.0.0.1:9090/cu/?wsdl', retrying as a local file");
            logger.warning(e.getMessage());
        }
        CHECKUSERSERVICE_WSDL_LOCATION = url;
    }

    public CheckUserService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public CheckUserService() {
        super(CHECKUSERSERVICE_WSDL_LOCATION, new QName("http://www.example.org/check/", "CheckUserService"));
    }

    /**
     * 
     * @return
     *     returns ICheckUserService
     */
    @WebEndpoint(name = "CheckUserPort")
    public ICheckUserService getCheckUserPort() {
        return super.getPort(new QName("http://www.example.org/check/", "CheckUserPort"), ICheckUserService.class);
    }

    /**
     * 
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *     returns ICheckUserService
     */
    @WebEndpoint(name = "CheckUserPort")
    public ICheckUserService getCheckUserPort(WebServiceFeature... features) {
        return super.getPort(new QName("http://www.example.org/check/", "CheckUserPort"), ICheckUserService.class, features);
    }

}

编写客户端测试类
package qlj.service.test;

import java.net.URL;

import javax.xml.namespace.QName;

import org.example.check.CheckUserService;
import org.example.check.ICheckUserService;

public class Test_client {

	public static void main(String[] args) throws Exception {
		String namespace = "http://www.example.org/check/";
		QName qName = new QName(namespace, "CheckUserService");
		URL url = new URL("http://127.0.0.1:9090/cu/?wsdl");
		CheckUserService checkUserService = new CheckUserService(url,qName);
		ICheckUserService iCheckUserService = checkUserService.getCheckUserPort();
		boolean isExist = iCheckUserService.checkUser("aa");
		System.out.println(isExist);
	}
}

运行结果如下
客户端输出结果true
服务端运行结果aa

结论:正确。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值