[CXF] Server与Client实现方式三:Provider-Dispatch
@WebServiceProvider(wsdlLocation = "DemoProvider.wsdl") //specify wsdl path@ServiceMode(value = Mode.MESSAGE) //specify service modepublic class OrderProcessDomProvider implements Provider<DOMSource> {@ResourceWebServiceContext context; //inject contextpublic DOMSource invoke(DOMSource request) {try {System.out.println(context.getMessageContext().get(Message.WSDL_OPERATION)); //get request operation//get requestMessageFactory factory = MessageFactory.newInstance();SOAPMessage message = factory.createMessage();message.getSOAPPart().setContent(request);message.writeTo(System.out);//construct responseSOAPMessage response = factory.createMessage();SOAPElement bodyElement = response.getSOAPBody().addChildElement(new QName("<namespace>", "<responseElement>", "<localpart>"));SOAPElement outElement = bodyElement.addChildElement("<reponseChildElement");outElement.setTextContent("output");DOMSource domSource = new DOMSource();domSource.setNode(response.getSOAPPart());return domSource;} catch (SOAPException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}}
上示代码中,注入了WebServiceContext用于访问与请求相关的各种信息,例如operation name,然后打印了请求信息,接下来根据wsdl中response schema的信息构造返回结果。注意这里的DomSource即是请求信息格式,也是返回信息格式。
?
和Provider端类,在Dispatch端需要根据request schema的结构构造请求信息内容,然后使用Dispatch将信息发送:
URL wsdlURL = new URL("DemoProvider.wsdl");Service service = Service.create(wsdlURL, new QName("<namespace>", "<serviceName>"));Dispatch<DOMSource> dispatch = service.createDispatch(new QName("<namespace>", "<portName>"),DOMSource.class, Service.Mode.MESSAGE);//set endpoint addressdispatch.getRequestContext().put(Dispatch.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8090/orderProcessProvider");//create request messageMessageFactory factory = MessageFactory.newInstance();SOAPMessage soapMessage = factory.createMessage();SOAPBody soapBody = soapMessage.getSOAPBody();SOAPElement requestElement = soapBody.addChildElement(new QName("<namespace>","<requestElement>", "<localpart>"));SOAPElement inElement = requestElement.addChildElement(new QName("<child>"));inElement.setTextContent("Input");DOMSource source = new DOMSource();source.setNode(soapMessage.getSOAPPart());//invokeDOMSource result = dispatch.invoke(source);//show resultSOAPMessage responseMsg = factory.createMessage();responseMsg.getSOAPPart().setContent(result);responseMsg.writeTo(System.out);
?
Endpoint.publish("http://localhost:8090/orderProcessProvider",new OrderProcessDomProvider());
?