cxf服务端创建与客户端调用和动态调用

1。服务端的创建

首先我们写一个服务接口,这个接口有一个sayHi的操作。

cxf服务端创建与客户端调用和动态调用_第1张图片

jaxb是不支持maps的,处理List很方便,但是不直接支持maps,需要一个适配器。

IntegerUserMapAdapter的作用是完成Map到IntegerUserMap的映射和
IntegerUserMap到Map的映射。方法分别是marshal和unmarshal

cxf服务端创建与客户端调用和动态调用_第2张图片



如果我们想保证参数在wsdl文件中是正确的可以使用下面的注解,否则参数就是arg0

cxf服务端创建与客户端调用和动态调用_第3张图片


下面写接口的实现

cxf服务端创建与客户端调用和动态调用_第4张图片

发布服务

cxf服务端创建与客户端调用和动态调用_第5张图片

然后就可以在http://localhost:9000/helloWorld?wsdl这个地址看到发布的服务了。


2.客户端的创建

第一种方式:

cxf服务端创建与客户端调用和动态调用_第6张图片

第二行和第三行代码可以不写

第二种方式:

动态调用

 */
public class Test4 {

    private static final QName SERVICE_NAME
            = new QName("http://server.hw.demo/",
            "HelloWorld");

    public static void main(String[] args) throws Exception {
        // 创建动态客户端
        JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
        Client client = factory.createClient("http://localhost:9000/helloWorld?wsdl", SERVICE_NAME);
        ClientImpl clientImpl = (ClientImpl) client;
        Endpoint endpoint = clientImpl.getEndpoint();
        List serviceInfos=endpoint.getService().getServiceInfos();
        ServiceInfo serviceInfo = endpoint.getService().getServiceInfos().get(0);
        QName bindingName = new QName("http://server.hw.demo/",
                "HelloWorldSoapBinding");
        BindingInfo binding = serviceInfo.getBinding(bindingName);
        QName opName = new QName("http://server.hw.demo/", "sayHiToUser");
        BindingOperationInfo boi = binding.getOperation(opName);
        BindingMessageInfo inputMessageInfo =null;
        if (!boi.isUnwrapped()) {
            //OrderProcess uses document literal wrapped style.
            inputMessageInfo = boi.getWrappedOperation().getInput();
        } else {
            inputMessageInfo = boi.getUnwrappedOperation().getInput();
        }
        List parts = inputMessageInfo.getMessageParts();
        // only one part.
        MessagePartInfo partInfo = parts.get(0);
        Class partClass = partInfo.getTypeClass();
        System.out.println(partClass.getCanonicalName()); // GetAgentDetails
        Object inputObject = partClass.newInstance();
        // 取得字段的set方法并赋值
//        PropertyDescriptor partPropertyDescriptor = new PropertyDescriptor("age", partClass);
//        Method userNoSetter = partPropertyDescriptor.getWriteMethod();
//        userNoSetter.invoke(inputObject,"20");
//
        // 取得字段的set方法并赋值
        PropertyDescriptor partPropertyDescriptor2 = new PropertyDescriptor("name", partClass);
        Method productCodeSetter = partPropertyDescriptor2.getWriteMethod();
        productCodeSetter.invoke(inputObject,"lgx");
        Object[] result = client.invoke(opName, inputObject);
        System.out.println(result[0]);

你可能感兴趣的:(webservice)